diff --git a/embedded-wallets/dashboard/README.mdx b/embedded-wallets/dashboard/README.mdx index b4721dc8414..bbe58f65152 100644 --- a/embedded-wallets/dashboard/README.mdx +++ b/embedded-wallets/dashboard/README.mdx @@ -49,7 +49,13 @@ The project comes pre-configured with default connections, chains and networks t Once your project is created, you can configure various aspects of your integration through the dashboard: -- **[Project Settings](./project-settings)** - Configure general settings, domain whitelisting, and advanced options +- **[Project Settings](./project-settings)** - Basic project information, credentials, and token verification +- **[Whitelist Settings](./whitelist)** - Domain and URL authorization for enhanced security +- **[Advanced Project Settings](./advanced/session-management)** - Advanced configuration options + - **[Session Management](./advanced/session-management)** - Session duration and behavior + - **[Test Accounts](./advanced/test-accounts)** - Development testing environment + - **[User Details in ID Token](./advanced/user-details)** - JWT token user data configuration + - **[Key Export Settings](./advanced/key-export)** - Private key export permissions - **[Chains and Networks](./chains-and-networks)** - Manage blockchain networks and custom chain configurations - **[Authentication](./authentication)** - Configure login methods, social connections, and custom authentication - **[Wallet Services](./wallet-services)** - Customize wallet UI and configure wallet features diff --git a/embedded-wallets/dashboard/advanced/key-export.mdx b/embedded-wallets/dashboard/advanced/key-export.mdx new file mode 100644 index 00000000000..96c7377fde3 --- /dev/null +++ b/embedded-wallets/dashboard/advanced/key-export.mdx @@ -0,0 +1,452 @@ +--- +title: Key Export Settings +sidebar_label: Key Export +image: 'img/metamaskog.jpg' +description: 'Configure private key export permissions in Web3Auth Dashboard | Embedded Wallets' +--- + +import ProjectSettingsAdvanced from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png' + +The **Key Export Settings** allow you to control whether users can programmatically export their private keys using the Web3Auth SDK. This setting provides flexibility for advanced use cases while maintaining security control over sensitive cryptographic material. + +
+ Key Export Settings +
+ +## Key Export Overview + +Private key export functionality allows applications to retrieve users' private keys programmatically through the Web3Auth SDK. This capability enables advanced use cases such as wallet migration, multi-platform support, and integration with external services, while requiring careful consideration of security implications. + +### Export Methods + +**Programmatic Export (Configurable):** + +- Access via `eth_private_key` JSON-RPC method +- Requires explicit user consent +- Can be enabled/disabled per project +- Controlled through dashboard settings + +**Manual Export (Always Available):** + +- Built-in Web3Auth wallet interface +- User-initiated through wallet UI +- Cannot be disabled +- Provides user autonomy over their keys + +## Configuring Key Export + +### Enabling Programmatic Export + +1. **Navigate to Project Settings** → **Advanced** → **Key Export** +2. **Locate "Enable Key Export"** toggle +3. **Enable the setting** to allow programmatic access +4. **Save configuration** to apply changes + +### Disabling Programmatic Export + +When disabled: + +- Applications cannot retrieve private keys via SDK +- Users can still export manually through wallet interface +- Enhanced security for applications that don't require key access +- Recommended for most consumer applications + +## Implementation Guide + +### Programmatic Key Retrieval + +**Basic Implementation:** + +```javascript +// Ensure user is authenticated +if ((await web3auth.status) !== 'connected') { + throw new Error('User not authenticated') +} + +// Request private key (requires user consent) +try { + const privateKey = await web3auth.provider.request({ + method: 'eth_private_key', + }) + + // Handle the private key securely + console.log('Private key retrieved successfully') + return privateKey +} catch (error) { + // Handle export rejection or failure + console.error('Key export failed:', error) + throw error +} +``` + +**Secure Implementation Pattern:** + +```javascript +class SecureKeyManager { + async exportKey() { + // Validate authentication state + await this.validateAuthentication() + + // Show user confirmation dialog + const userConsent = await this.getUserConsent() + if (!userConsent) { + throw new Error('User declined key export') + } + + // Retrieve private key + const privateKey = await web3auth.provider.request({ + method: 'eth_private_key', + }) + + // Process key securely (encrypt, transmit, etc.) + return await this.processKeySecurely(privateKey) + } + + async processKeySecurely(privateKey) { + // Implement your secure processing logic + // Examples: encryption, secure transmission, temporary storage + + // Always clear sensitive data from memory + setTimeout(() => { + privateKey = null + }, 0) + } +} +``` + +### User Consent Flow + +**Best Practices for User Consent:** + +```javascript +async function requestKeyExport() { + // Show clear explanation to user + const consent = await showConsentDialog({ + title: 'Export Private Key', + message: + 'Your private key will be exported for wallet migration. ' + + 'Keep this key secure and never share it with others.', + risks: [ + 'Anyone with your private key can access your funds', + 'Store the key in a secure location', + 'Consider using a hardware wallet for long-term storage', + ], + confirmText: 'I understand the risks and want to export my key', + cancelText: 'Cancel', + }) + + if (consent) { + return await exportPrivateKey() + } + + throw new Error('User declined key export') +} +``` + +## Use Cases for Key Export + +### Wallet Migration + +**Cross-Platform Migration:** + +```javascript +// Export from Web3Auth for import into other wallets +async function migrateToExternalWallet() { + try { + const privateKey = await exportPrivateKey() + + // Generate wallet formats for different platforms + const walletFormats = { + metamask: generateMetaMaskFormat(privateKey), + trustwallet: generateTrustWalletFormat(privateKey), + hardware: generateHardwareWalletFormat(privateKey), + } + + return walletFormats + } catch (error) { + console.error('Migration failed:', error) + throw error + } +} +``` + +### Multi-Chain Support + +**Cross-Chain Key Derivation:** + +```javascript +async function deriveKeysForMultipleChains() { + const basePrivateKey = await exportPrivateKey() + + // Derive keys for different blockchain networks + const chainKeys = { + ethereum: deriveEthereumKey(basePrivateKey), + polygon: derivePolygonKey(basePrivateKey), + solana: deriveSolanaKey(basePrivateKey), + bitcoin: deriveBitcoinKey(basePrivateKey), + } + + return chainKeys +} +``` + +### Advanced Integrations + +**DeFi Protocol Integration:** + +```javascript +async function integrateDeFiProtocol() { + // Export key for direct protocol interaction + const privateKey = await exportPrivateKey() + + // Create wallet instance for advanced operations + const wallet = new ethers.Wallet(privateKey, provider) + + // Perform complex DeFi operations + await performAdvancedDeFiOperations(wallet) + + // Clear sensitive data + wallet.privateKey = null +} +``` + +### Backup and Recovery + +**Secure Backup Creation:** + +```javascript +async function createSecureBackup() { + const privateKey = await exportPrivateKey() + + // Encrypt private key for backup + const encryptedBackup = await encryptKey(privateKey, userPassword) + + // Store encrypted backup securely + await storeEncryptedBackup(encryptedBackup) + + // Provide recovery instructions to user + showBackupInstructions(encryptedBackup) +} +``` + +## Security Considerations + +### Application Security + +**Key Handling Best Practices:** + +- **Minimize Exposure**: Retrieve keys only when necessary +- **Secure Transmission**: Use HTTPS and encrypted channels +- **Memory Management**: Clear private keys from memory immediately after use +- **No Persistent Storage**: Never store private keys in databases or local storage +- **Audit Logging**: Log key export events for security monitoring + +**Implementation Security:** + +```javascript +class SecureKeyHandler { + constructor() { + this.keyBuffer = null + } + + async handleKeyExport() { + try { + // Secure key retrieval + this.keyBuffer = await this.getPrivateKey() + + // Process immediately + const result = await this.processKey(this.keyBuffer) + + return result + } finally { + // Always clear sensitive data + this.clearKeyBuffer() + } + } + + clearKeyBuffer() { + if (this.keyBuffer) { + // Overwrite memory with random data + crypto.getRandomValues(new Uint8Array(this.keyBuffer.length)) + this.keyBuffer = null + } + } +} +``` + +### User Education + +**Security Awareness:** + +- Educate users about private key security +- Explain the implications of key export +- Provide secure storage recommendations +- Warn against sharing private keys + +**User Interface Guidelines:** + +```javascript +const securityWarnings = { + beforeExport: [ + 'Your private key controls access to your wallet and funds', + 'Never share your private key with anyone', + 'Store your key in a secure, offline location', + 'Consider using a hardware wallet for long-term storage', + ], + + afterExport: [ + 'Your private key has been exported', + 'Ensure it is stored securely and never shared', + 'Delete any temporary copies or screenshots', + 'Consider this key compromised if viewed by others', + ], +} +``` + +### Regulatory Compliance + +**Compliance Considerations:** + +- **Data Protection**: Ensure key export complies with privacy regulations +- **Audit Requirements**: Maintain records of key export events +- **User Consent**: Obtain explicit consent for key export operations +- **Jurisdictional Laws**: Consider local regulations regarding cryptographic material + +## Monitoring and Analytics + +### Export Event Tracking + +**Analytics Implementation:** + +```javascript +async function trackKeyExport(userId, exportReason) { + await analytics.track('private_key_exported', { + user_id: userId, + timestamp: new Date().toISOString(), + reason: exportReason, + user_agent: navigator.userAgent, + ip_address: await getUserIP(), + session_id: getSessionId(), + }) +} +``` + +**Security Monitoring:** + +```javascript +class KeyExportMonitor { + constructor() { + this.exportAttempts = new Map() + } + + async monitorExport(userId) { + const attempts = this.exportAttempts.get(userId) || 0 + + // Flag suspicious activity + if (attempts > 5) { + await this.flagSuspiciousActivity(userId) + } + + // Track export attempt + this.exportAttempts.set(userId, attempts + 1) + + // Reset counter after 24 hours + setTimeout( + () => { + this.exportAttempts.delete(userId) + }, + 24 * 60 * 60 * 1000 + ) + } +} +``` + +## Alternative Approaches + +### When to Disable Key Export + +**Recommended for:** + +- Consumer-facing applications +- Applications handling high-value assets +- Regulated financial services +- Applications with strict security requirements + +**Alternative Solutions:** + +- Use Web3Auth's built-in wallet interface +- Implement transaction signing without key exposure +- Use multi-signature schemes +- Leverage Web3Auth's session-based authentication + +### Transaction-Only Access + +**Secure Transaction Pattern:** + +```javascript +// Sign transactions without exposing private key +async function signTransaction(transactionData) { + // Use Web3Auth's provider directly + const signedTransaction = await web3auth.provider.request({ + method: 'eth_signTransaction', + params: [transactionData], + }) + + return signedTransaction +} +``` + +## Troubleshooting + +### Common Issues + +**Key Export Disabled:** + +- Verify setting is enabled in dashboard +- Check project configuration +- Confirm user permissions + +**Export Method Not Available:** + +- Ensure Web3Auth SDK is properly initialized +- Verify user is authenticated +- Check for browser compatibility issues + +**User Consent Failures:** + +- Implement proper consent flow +- Provide clear security information +- Handle user rejection gracefully + +### Error Handling + +**Robust Error Management:** + +```javascript +async function safeKeyExport() { + try { + await validateExportPermissions() + const key = await exportPrivateKey() + return key + } catch (error) { + if (error.code === 'EXPORT_DISABLED') { + throw new Error('Key export is disabled for this project') + } else if (error.code === 'USER_REJECTED') { + throw new Error('User declined key export') + } else { + console.error('Unexpected error:', error) + throw new Error('Key export failed') + } + } +} +``` + +## Next Steps + +- **[User Details in ID Token](./user-details)** - Configure user data in JWT tokens +- **[Session Management](./session-management)** - Control session duration and behavior +- **[Project Settings](../project-settings)** - Configure basic project information diff --git a/embedded-wallets/dashboard/advanced/session-management.mdx b/embedded-wallets/dashboard/advanced/session-management.mdx new file mode 100644 index 00000000000..555dae7275d --- /dev/null +++ b/embedded-wallets/dashboard/advanced/session-management.mdx @@ -0,0 +1,360 @@ +--- +title: Session Management +sidebar_label: Session Management +image: 'img/metamaskog.jpg' +description: 'Configure session duration and behavior in Web3Auth Dashboard | Embedded Wallets' +--- + +import ProjectSettingsAdvanced from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png' + +The **Session Management** settings allow you to customize session lifetime and behavior for your Web3Auth integration. These settings determine how long user sessions remain active before requiring re-authentication, providing flexibility to balance security requirements with user experience. + +
+ Session Management Settings +
+ +## Session Duration Overview + +Session duration controls how long a user's authentication session remains valid before automatic expiration. This setting directly impacts both security posture and user convenience, making it a critical configuration for production applications. + +### Default Configuration + +- **Default Duration**: 1 day (24 hours) +- **Minimum Duration**: 1 second +- **Maximum Duration**: 30 days (720 hours) +- **Granularity**: Configurable down to the second + +## Configuring Session Duration + +### Setting Session Lifetime + +1. **Navigate to Project Settings** → **Advanced** → **Session Management** +2. **Locate Session Duration** setting +3. **Enter desired duration** in the provided format +4. **Save configuration** to apply changes + +### Duration Format Options + +**Time Units Supported:** + +- **Seconds**: 1s, 30s, 60s +- **Minutes**: 1m, 30m, 60m +- **Hours**: 1h, 12h, 24h +- **Days**: 1d, 7d, 30d + +**Example Configurations:** + +``` +30m # 30 minutes +2h # 2 hours +1d # 1 day (default) +7d # 7 days +30d # 30 days (maximum) +``` + +## Security Considerations + +### Short Session Durations + +**Benefits:** + +- **Enhanced Security**: Reduced exposure window if credentials are compromised +- **Compliance**: Meets strict security requirements for sensitive applications +- **Risk Mitigation**: Limits potential damage from unauthorized access +- **Regular Validation**: Ensures users are actively using the application + +**Use Cases:** + +- Financial applications +- Healthcare systems +- Administrative interfaces +- High-security environments + +**Recommended Durations:** + +- **High Security**: 30m - 2h +- **Financial Apps**: 1h - 4h +- **Admin Panels**: 2h - 8h + +### Long Session Durations + +**Benefits:** + +- **Improved UX**: Reduces authentication friction for users +- **Productivity**: Minimizes workflow interruptions +- **User Retention**: Decreases abandonment due to re-authentication +- **Convenience**: Better for applications with frequent usage + +**Use Cases:** + +- Consumer applications +- Gaming platforms +- Content consumption apps +- Productivity tools + +**Recommended Durations:** + +- **Consumer Apps**: 7d - 30d +- **Gaming**: 14d - 30d +- **Content Apps**: 7d - 30d + +## Application-Specific Recommendations + +### Web Applications + +**Standard Web Apps:** + +``` +Session Duration: 1d - 7d +Rationale: Balance between security and convenience +``` + +**Single Page Applications (SPAs):** + +``` +Session Duration: 4h - 1d +Rationale: Active browsing sessions with automatic renewal +``` + +**Progressive Web Apps (PWAs):** + +``` +Session Duration: 7d - 30d +Rationale: App-like experience with persistent sessions +``` + +### Mobile Applications + +**Native Mobile Apps:** + +``` +Session Duration: 14d - 30d +Rationale: Device-based security with biometric re-authentication +``` + +**Mobile Games:** + +``` +Session Duration: 30d +Rationale: Seamless gaming experience with maximum convenience +``` + +**Financial Mobile Apps:** + +``` +Session Duration: 1h - 4h +Rationale: High security requirements with biometric backup +``` + +### Gaming Applications + +**Casual Games:** + +``` +Session Duration: 30d +Rationale: Minimal friction for entertainment applications +``` + +**Competitive Games:** + +``` +Session Duration: 14d - 30d +Rationale: Balance between convenience and account security +``` + +**Gaming Platforms:** + +``` +Session Duration: 7d - 30d +Rationale: Platform-level access with game-specific security +``` + +## Advanced Session Behaviors + +### Session Renewal + +Web3Auth sessions can be renewed through various mechanisms: + +**Automatic Renewal:** + +- Sessions automatically extend on user activity +- Background refresh maintains active sessions +- Seamless experience without user intervention + +**Manual Renewal:** + +- Explicit user action required for session extension +- Greater control over session lifecycle +- Suitable for high-security environments + +### Session Termination + +**Automatic Termination Events:** + +- Session duration expiry +- Extended inactivity periods +- Security-triggered logout +- Device/browser changes + +**Manual Termination:** + +- User-initiated logout +- Administrative session termination +- Forced logout from dashboard + +## Implementation Considerations + +### Frontend Integration + +**Session Status Monitoring:** + +```javascript +// Check session status +const isAuthenticated = await web3auth.status + +// Handle session expiry +web3auth.on('session_expired', () => { + // Redirect to login or show re-authentication modal + handleSessionExpiry() +}) +``` + +**Graceful Session Handling:** + +```javascript +// Monitor session state +setInterval(async () => { + const sessionValid = await web3auth.isLoggedIn() + if (!sessionValid) { + // Handle session expiry gracefully + await handleSessionExpiry() + } +}, 60000) // Check every minute +``` + +### Backend Validation + +**Token Validation:** + +```javascript +import jwt from 'jsonwebtoken' + +// Validate session token +function validateSession(token) { + try { + const decoded = jwt.verify(token, publicKey) + const now = Math.floor(Date.now() / 1000) + + if (decoded.exp < now) { + throw new Error('Session expired') + } + + return decoded + } catch (error) { + // Handle session validation failure + throw new Error('Invalid session') + } +} +``` + +## Security Best Practices + +### Session Security Guidelines + +**Token Management:** + +- Store session tokens securely (HttpOnly cookies for web) +- Implement proper token rotation +- Use secure transmission (HTTPS only) +- Clear tokens on logout + +**Monitoring and Alerting:** + +- Track unusual session patterns +- Monitor concurrent sessions +- Alert on suspicious activity +- Log session events for audit + +**Multi-Device Considerations:** + +- Limit concurrent sessions per user +- Implement device fingerprinting +- Provide session management UI +- Enable remote session termination + +### Compliance Requirements + +**Industry Standards:** + +- **PCI DSS**: Maximum 15-minute idle timeout for payment systems +- **HIPAA**: Regular session timeouts for healthcare data +- **SOX**: Documented session management for financial systems +- **GDPR**: User control over session data and duration + +**Risk Assessment Matrix:** + +| Risk Level | Max Session Duration | Re-auth Frequency | +| ---------- | -------------------- | ----------------- | +| Critical | 1-2 hours | Every action | +| High | 2-8 hours | Daily | +| Medium | 1-7 days | Weekly | +| Low | 7-30 days | Monthly | + +## Troubleshooting Session Issues + +### Common Session Problems + +**Premature Session Expiry:** + +- Check system clock synchronization +- Verify session duration configuration +- Review token validation logic +- Check for timezone issues + +**Sessions Not Expiring:** + +- Confirm session duration settings +- Check automatic renewal behavior +- Verify backend token validation +- Review frontend session monitoring + +**Inconsistent Session Behavior:** + +- Check cross-device synchronization +- Verify token storage mechanisms +- Review session renewal logic +- Test different browser/app configurations + +### Debugging Tools + +**Session Inspection:** + +```javascript +// Debug session information +console.log('Session Duration:', web3auth.sessionDuration) +console.log('Session Start:', web3auth.sessionStartTime) +console.log('Session Expires:', web3auth.sessionExpiryTime) +console.log('Time Remaining:', web3auth.sessionTimeRemaining) +``` + +**Token Analysis:** + +```javascript +// Decode and inspect session token +const jwt = require('jsonwebtoken') +const decoded = jwt.decode(sessionToken, { complete: true }) +console.log('Token Header:', decoded.header) +console.log('Token Payload:', decoded.payload) +console.log('Issued At:', new Date(decoded.payload.iat * 1000)) +console.log('Expires At:', new Date(decoded.payload.exp * 1000)) +``` + +## Next Steps + +- **[Key Export Settings](./key-export)** - Configure private key export permissions +- **[User Details in ID Token](./user-details)** - Manage user data in JWT tokens +- **[Project Settings](../project-settings)** - Configure basic project information diff --git a/embedded-wallets/dashboard/advanced/test-accounts.mdx b/embedded-wallets/dashboard/advanced/test-accounts.mdx new file mode 100644 index 00000000000..b1e047f9e33 --- /dev/null +++ b/embedded-wallets/dashboard/advanced/test-accounts.mdx @@ -0,0 +1,102 @@ +--- +title: Test Accounts +sidebar_label: Test Accounts +image: 'img/metamaskog.jpg' +description: 'Configure test accounts for development and testing | Embedded Wallets' +--- + +import TestAccountsSettings from '@site/static/img/embedded-wallets/w3a-dashboard/test-accounts-settings.png' + +Test Accounts allow you to log in with static verification codes during development and testing phases. This feature simplifies the authentication flow when testing your application by providing predictable OTP codes and designated test credentials. + +Enabling this option permits login through the provided email, OTP code, or phone number. Note that these accounts are designated for testing only and should not be used in production/ storing funds. + +
+ Test Accounts Settings +
+ +## Enabling Test Accounts + +Test Accounts can be enabled through the Web3Auth Dashboard: + +1. Navigate to your project in the [Web3Auth Dashboard](https://dashboard.web3auth.io) +2. Go to **Project Settings** > **Advanced** +3. Locate the **Test Accounts** section +4. Toggle the **Enable Test Accounts** option + +## Test Account Types + +### Email Authentication + +When Test Accounts are enabled, each test account is assigned a unique email address in the format `test_account_XXXX@example.com`, where `XXXX` represents a randomly generated number. You can use these test email addresses to authenticate using email passwordless OTP login. + +### Phone Number Authentication + +When Test Accounts are enabled, each test account is assigned a unique phone number in the format `+1 (555) XXX-XXXX`, where `XXX-XXXX` represents a randomly generated number. You can use these test phone numbers to authenticate using SMS OTP login. + +### Static OTP Code + +When using Test Accounts, a static OTP verification code is generated and displayed in your project dashboard. This code remains constant for both email and phone number test accounts. + +## Usage in Development + +### Email + OTP Flow + +1. Enter a test email (e.g., `test_account_XXXX@example.com`) +2. Click "Send Code" or equivalent button +3. Enter the static OTP: `XXXXXX` +4. Complete the authentication flow + +### SMS + OTP Flow + +1. Enter a test phone number (e.g., `+1 (555) XXX-XXXX`) +2. Click "Send Code" or equivalent button +3. Enter the static OTP: `XXXXXX` +4. Complete the authentication flow + +## Benefits for Development + +### Consistent Testing Experience + +- **Predictable Credentials**: Same OTP code (`XXXXXX`) works every time +- **No External Dependencies**: No need to access email or SMS during testing +- **Faster Iteration**: Streamlined testing without waiting for delivery of verification codes + +### Team Collaboration + +- **Shared Test Accounts**: Team members can use the same test credentials +- **Standardized Testing**: Consistent testing experience across the development team +- **Demo-Friendly**: Reliable for demonstrations and presentations + +### CI/CD Integration + +- **Automated Testing**: Enables automated tests that require authentication flows +- **E2E Testing**: Facilitates end-to-end testing scenarios +- **Staging Validation**: Supports testing in staging environments + +## Security Considerations + +### Best Practices + +- **Never use Test Accounts in production** - they are designed for testing only and could expose your application to security vulnerabilities if used in production +- **Disable before going live** - ensure Test Accounts are turned off before production deployment +- **Use separate projects** - maintain separate projects for development and production environments +- **Document test credentials** - clearly document which credentials are for testing only + +### Troubleshooting + +If Test Accounts are not functioning as expected: + +1. **Verify Environment**: Ensure you're using your particular Sapphire Devnet or Sapphire Mainnet environment where test accounts are enabled. +2. **Check Project Settings**: Confirm Test Accounts are enabled in Project Settings > Advanced +3. **Email or Phone**: Ensure test email or phone number is correct as mentioned in the dashboard, you can refresh the credentials by clicking on the refresh button. +4. **OTP Code**: Always use `XXXXXX` as the verification code as mentioned in the dashboard diff --git a/embedded-wallets/dashboard/advanced/user-details.mdx b/embedded-wallets/dashboard/advanced/user-details.mdx new file mode 100644 index 00000000000..96d623fb97a --- /dev/null +++ b/embedded-wallets/dashboard/advanced/user-details.mdx @@ -0,0 +1,618 @@ +--- +title: User Details in ID Token +sidebar_label: User Details +image: 'img/metamaskog.jpg' +description: 'Configure user data in JWT identity tokens | Embedded Wallets' +--- + +import ProjectSettingsAdvanced from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png' + +The **User Details in ID Token** setting determines whether Personally Identifiable Information (PII)—such as the user's email, profile picture, and name—is returned in the JWT identity token issued by Web3Auth. This configuration allows you to control the level of user information available directly within the authentication token. + +
+ User Details Settings +
+ +## User Data Overview + +JWT identity tokens can include various types of user information, ranging from minimal identifiers to comprehensive profile data. The configuration of this setting impacts both functionality and privacy considerations for your application. + +### Available User Data Types + +**Basic Identifier Information:** + +- User ID (always included) +- Wallet address (always included) +- Authentication timestamp (always included) + +**Optional Profile Information:** + +- Email address +- Full name +- Profile picture URL +- Social login provider data +- Custom user metadata + +## Configuration Options + +### Enable User Data in Tokens + +When **enabled**, the identity token includes comprehensive user profile information: + +```json +{ + "iss": "https://api.web3auth.io", + "sub": "user_unique_identifier", + "aud": "your_client_id", + "exp": 1640995200, + "iat": 1640908800, + "email": "user@example.com", + "name": "John Doe", + "picture": "https://profile-pics.com/user.jpg", + "provider": "google", + "wallet_address": "0x1234567890abcdef...", + "custom_data": { + "user_tier": "premium", + "registration_date": "2023-01-15" + } +} +``` + +### Disable User Data in Tokens + +When **disabled**, the identity token contains only essential identification information: + +```json +{ + "iss": "https://api.web3auth.io", + "sub": "user_unique_identifier", + "aud": "your_client_id", + "exp": 1640995200, + "iat": 1640908800, + "wallet_address": "0x1234567890abcdef..." +} +``` + +### Email-Only Mode + +When **userIdentifier is set to email**, only the user's email is included in the token: + +```json +{ + "iss": "https://api.web3auth.io", + "sub": "user_unique_identifier", + "aud": "your_client_id", + "exp": 1640995200, + "iat": 1640908800, + "email": "user@example.com", + "wallet_address": "0x1234567890abcdef..." +} +``` + +## Implementation Patterns + +### Token Parsing and Validation + +**Complete Token Processing:** + +```javascript +import jwt from 'jsonwebtoken' + +async function processUserToken(idToken) { + try { + // Verify and decode the token + const decoded = jwt.verify(idToken, publicKey, { + issuer: 'https://api.web3auth.io', + audience: 'your_client_id', + }) + + // Extract user information + const userProfile = { + id: decoded.sub, + walletAddress: decoded.wallet_address, + email: decoded.email || null, + name: decoded.name || null, + picture: decoded.picture || null, + provider: decoded.provider || null, + customData: decoded.custom_data || {}, + } + + return userProfile + } catch (error) { + console.error('Token validation failed:', error) + throw new Error('Invalid user token') + } +} +``` + +**Conditional Data Handling:** + +```javascript +function extractUserData(decodedToken) { + const baseData = { + userId: decodedToken.sub, + walletAddress: decodedToken.wallet_address, + issuedAt: new Date(decodedToken.iat * 1000), + expiresAt: new Date(decodedToken.exp * 1000), + } + + // Handle optional profile data + if (decodedToken.email) { + baseData.email = decodedToken.email + } + + if (decodedToken.name) { + baseData.displayName = decodedToken.name + } + + if (decodedToken.picture) { + baseData.profilePicture = decodedToken.picture + } + + if (decodedToken.custom_data) { + baseData.metadata = decodedToken.custom_data + } + + return baseData +} +``` + +### Frontend Integration + +**React Implementation:** + +```jsx +import { useEffect, useState } from 'react' +import { Web3Auth } from '@web3auth/modal' + +function UserProfile() { + const [userInfo, setUserInfo] = useState(null) + + useEffect(() => { + const loadUserData = async () => { + if (web3auth.status === 'connected') { + // Get ID token with user data + const idToken = await web3auth.authenticateUser() + + // Parse user information from token + const userProfile = parseUserToken(idToken.idToken) + setUserInfo(userProfile) + } + } + + loadUserData() + }, []) + + if (!userInfo) { + return
Loading user profile...
+ } + + return ( +
+ {userInfo.picture && Profile} + {userInfo.name &&

{userInfo.name}

} + {userInfo.email &&

Email: {userInfo.email}

} +

Wallet: {userInfo.walletAddress}

+
+ ) +} +``` + +**Vue Implementation:** + +```vue + + + +``` + +## Use Cases and Benefits + +### Streamlined User Onboarding + +**Profile Pre-population:** + +```javascript +async function setupUserAccount(idToken) { + const userProfile = parseUserToken(idToken) + + // Pre-populate user profile from token data + const accountData = { + email: userProfile.email, + displayName: userProfile.name, + avatarUrl: userProfile.picture, + authProvider: userProfile.provider, + walletAddress: userProfile.walletAddress, + } + + // Create user account with pre-filled information + await createUserAccount(accountData) + + // Skip additional profile setup steps + redirectToMainApplication() +} +``` + +### Personalized User Experience + +**Dynamic UI Customization:** + +```javascript +function personalizeInterface(userProfile) { + // Customize greeting based on available name + const greeting = userProfile.name ? `Welcome back, ${userProfile.name}!` : `Welcome back!` + + // Update profile avatar + if (userProfile.picture) { + updateUserAvatar(userProfile.picture) + } + + // Apply user-specific settings + if (userProfile.customData?.theme) { + applyUserTheme(userProfile.customData.theme) + } + + // Show personalized content + displayPersonalizedContent(userProfile) +} +``` + +### Session Management + +**Enhanced Session Context:** + +```javascript +class SessionManager { + constructor(idToken) { + this.userProfile = parseUserToken(idToken) + this.sessionData = this.initializeSession() + } + + initializeSession() { + return { + userId: this.userProfile.id, + email: this.userProfile.email, + displayName: this.userProfile.name, + walletAddress: this.userProfile.walletAddress, + loginProvider: this.userProfile.provider, + sessionStart: new Date(), + lastActivity: new Date(), + } + } + + updateActivity() { + this.sessionData.lastActivity = new Date() + + // Log activity with user context + this.logUserActivity({ + userId: this.sessionData.userId, + email: this.sessionData.email, + action: 'page_view', + timestamp: new Date(), + }) + } +} +``` + +## Privacy and Compliance Considerations + +### Data Minimization Principles + +**GDPR Compliance:** + +- Only include necessary user data in tokens +- Obtain explicit consent for PII inclusion +- Provide clear privacy notices +- Enable data portability and deletion + +**Implementation Example:** + +```javascript +class PrivacyCompliantTokenHandler { + constructor(privacySettings) { + this.allowedFields = privacySettings.allowedTokenFields + this.userConsent = privacySettings.userConsent + } + + processUserToken(rawToken) { + const decodedToken = jwt.decode(rawToken) + const filteredData = {} + + // Only include fields user consented to + this.allowedFields.forEach(field => { + if (decodedToken[field] && this.userConsent[field]) { + filteredData[field] = decodedToken[field] + } + }) + + return filteredData + } +} +``` + +### Regional Compliance + +**Multi-Jurisdictional Considerations:** + +```javascript +function getRegionSpecificTokenHandling(userRegion) { + const regionPolicies = { + EU: { + requireExplicitConsent: true, + dataRetentionDays: 90, + allowProfilePictures: false, + requireDataProcessingNotice: true, + }, + US: { + requireExplicitConsent: false, + dataRetentionDays: 365, + allowProfilePictures: true, + requireDataProcessingNotice: false, + }, + APAC: { + requireExplicitConsent: true, + dataRetentionDays: 180, + allowProfilePictures: true, + requireDataProcessingNotice: true, + }, + } + + return regionPolicies[userRegion] || regionPolicies['EU'] // Default to strictest +} +``` + +## Security Considerations + +### Token Security Best Practices + +**Secure Token Handling:** + +```javascript +class SecureTokenProcessor { + constructor() { + this.tokenCache = new Map() + this.encryptionKey = process.env.TOKEN_ENCRYPTION_KEY + } + + async processToken(idToken) { + // Validate token signature + const isValid = await this.validateTokenSignature(idToken) + if (!isValid) { + throw new Error('Invalid token signature') + } + + // Check for token replay attacks + if (this.isTokenReplayed(idToken)) { + throw new Error('Token replay detected') + } + + // Extract and sanitize user data + const userData = this.extractUserData(idToken) + return this.sanitizeUserData(userData) + } + + sanitizeUserData(userData) { + // Remove potentially dangerous content + const sanitized = { ...userData } + + if (sanitized.name) { + sanitized.name = this.sanitizeString(sanitized.name) + } + + if (sanitized.email) { + sanitized.email = this.validateEmail(sanitized.email) + } + + if (sanitized.picture) { + sanitized.picture = this.validateImageUrl(sanitized.picture) + } + + return sanitized + } +} +``` + +### Data Validation + +**Input Validation and Sanitization:** + +```javascript +function validateUserData(userData) { + const validators = { + email: email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email), + name: name => name.length <= 100 && !/[<>]/.test(name), + picture: url => { + try { + const parsed = new URL(url) + return ['https:'].includes(parsed.protocol) + } catch { + return false + } + }, + } + + const validatedData = {} + + Object.keys(userData).forEach(key => { + if (validators[key]) { + if (validators[key](userData[key])) { + validatedData[key] = userData[key] + } else { + console.warn(`Invalid ${key} data:`, userData[key]) + } + } else { + validatedData[key] = userData[key] + } + }) + + return validatedData +} +``` + +## Performance Considerations + +### Token Size Management + +**Optimizing Token Size:** + +- Include only necessary user fields +- Avoid large profile pictures (use URLs instead) +- Limit custom metadata size +- Consider token size impact on network performance + +**Token Size Monitoring:** + +```javascript +function analyzeTokenSize(idToken) { + const tokenSize = new Blob([idToken]).size + const decoded = jwt.decode(idToken) + + const analysis = { + totalSize: tokenSize, + headerSize: JSON.stringify(decoded.header).length, + payloadSize: JSON.stringify(decoded.payload).length, + signatureSize: idToken.split('.')[2].length, + userDataSize: JSON.stringify({ + email: decoded.email, + name: decoded.name, + picture: decoded.picture, + custom_data: decoded.custom_data, + }).length, + } + + // Log warning for large tokens + if (tokenSize > 8192) { + // 8KB threshold + console.warn('Large JWT token detected:', analysis) + } + + return analysis +} +``` + +### Caching Strategies + +**Efficient User Data Caching:** + +```javascript +class UserDataCache { + constructor() { + this.cache = new Map() + this.ttl = 5 * 60 * 1000 // 5 minutes + } + + getUserData(userId, idToken) { + const cached = this.cache.get(userId) + + if (cached && Date.now() - cached.timestamp < this.ttl) { + return cached.data + } + + // Parse fresh token data + const userData = parseUserToken(idToken) + + // Cache with timestamp + this.cache.set(userId, { + data: userData, + timestamp: Date.now(), + }) + + return userData + } + + invalidateUser(userId) { + this.cache.delete(userId) + } + + clearExpired() { + const now = Date.now() + for (const [userId, cached] of this.cache.entries()) { + if (now - cached.timestamp >= this.ttl) { + this.cache.delete(userId) + } + } + } +} +``` + +## Decision Framework + +### When to Enable User Data in Tokens + +**Recommended for:** + +- Applications requiring immediate user context +- Single-page applications with limited backend calls +- Personalization-heavy interfaces +- Offline-capable applications + +**Consider enabling when:** + +- User onboarding needs profile pre-population +- UI personalization improves user experience +- Session management benefits from user context +- Reduced API calls for user data improve performance + +### When to Disable User Data in Tokens + +**Recommended for:** + +- High-security applications +- Compliance-heavy environments +- Applications with separate user management systems +- Minimal data exposure requirements + +**Consider disabling when:** + +- Privacy regulations are strict +- Token size is a concern +- User data is managed separately +- Security requirements prefer minimal token content + +### Email-Only Configuration + +**Optimal for:** + +- Applications needing user identification only +- Email-based user management systems +- Privacy-focused applications +- Minimal PII exposure scenarios + +## Next Steps + +- **[Session Management](./session-management)** - Configure session duration and behavior +- **[Key Export Settings](./key-export)** - Control private key export permissions +- **[Project Settings](../project-settings)** - Configure basic project information diff --git a/embedded-wallets/dashboard/project-settings.mdx b/embedded-wallets/dashboard/project-settings.mdx index a7843930ea2..760cdf29305 100644 --- a/embedded-wallets/dashboard/project-settings.mdx +++ b/embedded-wallets/dashboard/project-settings.mdx @@ -6,13 +6,9 @@ description: 'Configure project settings in Web3Auth Dashboard | Embedded Wallet --- import ProjectSettingsGeneral from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-general.png' -import ProjectSettingsDomain from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png' -import ProjectSettingsAdvanced from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png' The **Project Settings** section of the Web3Auth Dashboard allows developers to manage core configuration options for each project. These settings determine how the project integrates with the Web3Auth SDK and how it behaves across different environments. -## General -
-The **General tab** provides an overview of key project-specific parameters: +## Project Information -- **Project Name**: This is the name of the project that will be displayed to users during the Web3Auth login flow and in any related email communication. The name can be updated post-creation at any time. -- **Environment**: This indicates the Web3Auth environment (devnet or mainnet) selected during project creation. These environments are globally distributed and highly scalable. Once set, the environment cannot be modified. -- **Client ID**: A unique identifier automatically generated for each project. This value is required for SDK integration and is safe to expose publicly. -- **Client Secret**: A confidential key used for authenticating server-side API requests. It should never be exposed to the frontend or any client-side environment to maintain security. -- **JWKS Endpoint**: A public endpoint that exposes the JSON Web Key Set (JWKS) used by Web3Auth to sign JWTs. Developers can use this endpoint to verify identity tokens. [Learn more](#). -- **Project Verification Key**: An alternative to using the JWKS endpoint. This static key allows for token verification without depending on the JWKS URL. [Learn more](#). -- **Project Platform**: Developers can select from a wide range of platform options such as Web, Mobile, or Gaming, depending on the nature of the application. +### Project Name -### Archive Project +This is the name of the project that will be displayed to users during the Web3Auth login flow and in any related email communication. The project name serves as your application's identity in the Web3Auth ecosystem. -The Archive Project button allows developers to archive a project. Once archived, the project becomes read-only and cannot be modified unless explicitly restored. +**Key Features:** -## Whitelist Domains +- **User-Facing Display**: Appears in login modals and authentication flows +- **Email Communications**: Used in Web3Auth-generated emails to users +- **Dashboard Identification**: Helps you identify projects in your dashboard +- **Updateable**: Can be modified at any time after project creation -To enhance security, Web3Auth enables domain whitelisting for both web and mobile applications. +**Best Practices:** -- Domain Authorization Developers must add and verify URLs that are authorized to use the Web3Auth SDK. +- Use a clear, recognizable name that matches your application +- Keep it concise but descriptive +- Avoid special characters that might cause display issues +- Consider how it will appear to end users - > For mainnet projects, at least one domain or URL must be whitelisted before the SDK can be used in production. +### Environment - {" "} +This indicates the Web3Auth environment selected during project creation. The environment determines the infrastructure tier and security level of your project. -
- Project Settings Domains -
+**Available Environments:** -## Advanced +- **Sapphire Devnet**: Development environment for testing and integration +- **Sapphire Mainnet**: Production environment for live applications -The Advanced tab provides developers with additional configuration options to fine-tune authentication behavior, session control, and data privacy. +**Important Notes:** -
- Project Settings Advanced -
+- Environments are globally distributed and highly scalable +- **Cannot be modified** after project creation +- Each environment has separate user bases and data isolation +- Production applications should use Sapphire Mainnet + +### Project Platform + +Developers can select from a wide range of platform options depending on the nature of their application. This setting helps optimize the SDK behavior and available features for your specific platform. -### Session Duration +**Platform Options:** -Web3Auth allows customization of session lifetime: +- **Web**: Browser-based applications (React, Vue, JavaScript) +- **Mobile**: Native mobile applications (Android, iOS, React Native, Flutter) +- **Gaming**: Game development platforms (Unity, Unreal Engine) -- Developers can configure how long a user session remains active before requiring re-authentication. -- The default session duration is 1 day. -- Minimum configurable duration is 1 second, while the maximum is 30 days. +**Platform-Specific Features:** -This setting is particularly useful for balancing security and user experience. Shorter durations increase security by reducing exposure, while longer durations improve usability for trusted applications. +- Different SDK packages and integration methods +- Platform-optimized authentication flows +- Tailored documentation and examples +- Specific security considerations -### Return User Data in Identity Token +## Authentication Credentials -This option determines whether Personally Identifiable Information (PII)—such as the user's email, profile picture, and name—is returned in the JWT identity token issued by Web3Auth. +### Client ID + +A unique identifier automatically generated for each project. This is the primary credential used to authenticate your application with Web3Auth services. + +**Characteristics:** + +- **Publicly Safe**: Can be exposed in client-side code +- **Required for Integration**: Essential for all SDK implementations +- **Unique per Project**: Each project receives a distinct Client ID +- **Immutable**: Cannot be changed after generation + +**Usage Example:** + +```javascript +import { Web3Auth } from '@web3auth/modal' + +const web3auth = new Web3Auth({ + clientId: 'YOUR_CLIENT_ID_HERE', // Safe to expose publicly + web3AuthNetwork: 'sapphire_mainnet', +}) +``` -- Enabling this setting allows applications to access additional user metadata directly from the identity token. -- If userIdentifier is set to email, only the user's email will be returned in the token. This provides a privacy-centric approach to user identity management. +### Client Secret -> Why this matters: Including user PII in the JWT can streamline user onboarding, personalization, and session management in your application. However, developers must consider user consent, data minimization, and jurisdictional privacy regulations (such as GDPR or CCPA) before enabling this option. Only request what is essential for your application's functionality. +A confidential key used for authenticating server-side API requests and advanced integrations. This credential provides elevated access to Web3Auth services. -### Enable Key Export +**Security Requirements:** -This setting allows developers to control whether users can programmatically export their private keys using the Web3Auth SDK. +- **Never expose** in frontend code or client-side environments +- **Server-side only**: Use exclusively in backend services +- **Secure storage**: Store in environment variables or secure vaults +- **Rotation capability**: Can be regenerated if compromised -- When enabled, the application can allow users to retrieve their private key. For this, the dApp must use the `eth_private_key` JSON-RPC method. -- When disabled, users will only be able to export their keys manually via Web3Auth's built-in wallet interface. +**Use Cases:** -This functionality is crucial for advanced use cases such as migration, backup, or interoperability with non-EVM-compatible blockchains. +- Server-side user verification +- Administrative operations +- Webhook signature verification +- Advanced API integrations -> Example: Programmatically retrieving the private key after login: +:::danger Security Warning + +The Client Secret must never be exposed in client-side code, mobile applications, or any publicly accessible environment. Exposure could compromise your project's security. + +::: + +## Token Verification + +### JWKS Endpoint + +A public endpoint that exposes the JSON Web Key Set (JWKS) used by Web3Auth to sign JWTs. This endpoint enables you to verify the authenticity of identity tokens issued by Web3Auth. + +**Endpoint Format:** + +``` +https://api.web3auth.io/jwks?project_id=YOUR_PROJECT_ID +``` + +**Benefits:** + +- **Dynamic Key Rotation**: Automatically receives updated signing keys +- **Industry Standard**: JWKS is a widely adopted standard for JWT verification +- **High Availability**: Backed by Web3Auth's global infrastructure +- **Real-time Updates**: Always provides current verification keys + +**Implementation Example:** ```javascript -// Assuming user is already logged in -async function getPrivateKey() { - const privateKey = await web3auth.provider.request({ - method: 'eth_private_key', +import jwt from 'jsonwebtoken' +import jwksClient from 'jwks-rsa' + +const client = jwksClient({ + jwksUri: 'https://api.web3auth.io/jwks?project_id=YOUR_PROJECT_ID', +}) + +function getKey(header, callback) { + client.getSigningKey(header.kid, (err, key) => { + const signingKey = key.publicKey || key.rsaPublicKey + callback(null, signingKey) }) } + +// Verify token +jwt.verify(token, getKey, options, (err, decoded) => { + if (err) { + console.error('Token verification failed:', err) + } else { + console.log('Token verified:', decoded) + } +}) ``` + +### Project Verification Key + +An alternative to using the JWKS endpoint, this static key allows for token verification without depending on external JWKS URL calls. + +**Advantages:** + +- **Offline Verification**: No external API calls required +- **Reduced Latency**: Faster token verification process +- **Network Independence**: Works in environments with limited connectivity +- **Simplified Implementation**: Single key verification logic + +**When to Use:** + +- Applications with strict latency requirements +- Environments with limited internet access +- Simplified verification workflows +- Backup verification method + +**Implementation Example:** + +```javascript +import jwt from 'jsonwebtoken' + +const PROJECT_VERIFICATION_KEY = `-----BEGIN PUBLIC KEY----- +YOUR_PROJECT_VERIFICATION_KEY_HERE +-----END PUBLIC KEY-----` + +// Verify token with static key +jwt.verify(token, PROJECT_VERIFICATION_KEY, { algorithms: ['RS256'] }, (err, decoded) => { + if (err) { + console.error('Token verification failed:', err) + } else { + console.log('Token verified:', decoded) + } +}) +``` + +## Project Management + +### Archive Project + +The Archive Project feature allows you to deactivate a project while preserving its configuration and data. This is useful for temporarily disabling projects or maintaining historical records. + +**Archive Effects:** + +- **Read-Only Mode**: Project becomes non-functional but viewable +- **Authentication Disabled**: Users cannot log in to archived projects +- **Data Preservation**: All configuration and user data is retained +- **Reversible**: Projects can be restored from archived state + +**When to Archive:** + +- Temporary project suspension +- End-of-life applications +- Testing environment cleanup +- Compliance requirements + +**Restoration Process:** + +- Archived projects can be restored through the dashboard +- All settings and configurations are preserved +- User data and authentication flows resume normally +- No data loss occurs during archive/restore cycles + +:::info Archive vs Delete + +Archiving preserves all project data and allows for restoration. If you need to permanently remove a project, contact Web3Auth support for assistance with proper data deletion procedures. + +::: + +## Next Steps + +For comprehensive project configuration, explore these related settings: + +- **[Whitelist Settings](./whitelist)** - Configure domain and URL authorization for enhanced security +- **[Advanced Project Settings](./advanced/session-management)** - Access session management, key export, user data, and testing configurations + +### Quick Start Guide + +**Essential Configuration Steps:** + +1. Set up your project name and verify environment +2. Obtain your Client ID for SDK integration +3. Configure domain whitelisting for security +4. Set up token verification method +5. Review advanced settings as needed + +### Production Deployment Checklist + +- ✅ All production domains whitelisted +- ✅ Token verification configured +- ✅ Advanced settings reviewed +- ✅ Test accounts disabled +- ✅ Security settings verified diff --git a/embedded-wallets/dashboard/whitelist.mdx b/embedded-wallets/dashboard/whitelist.mdx new file mode 100644 index 00000000000..3b8f718db37 --- /dev/null +++ b/embedded-wallets/dashboard/whitelist.mdx @@ -0,0 +1,307 @@ +--- +title: Whitelist Settings +sidebar_label: Whitelist +image: 'img/metamaskog.jpg' +description: 'Configure domain whitelisting in Web3Auth Dashboard | Embedded Wallets' +--- + +import ProjectSettingsDomain from '@site/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png' + +The **Whitelist Settings** section allows you to configure domain and URL authorization for enhanced security. Web3Auth requires explicit whitelisting of domains and URLs that are authorized to use your project's Web3Auth SDK, providing protection against unauthorized usage and potential security threats. + +
+ Project Settings Domains +
+ +## Domain Authorization Overview + +Domain whitelisting is a critical security feature that prevents unauthorized applications from using your Web3Auth project credentials. Only domains and URLs explicitly added to your whitelist can successfully authenticate users through your Web3Auth configuration. + +### Security Benefits + +- **Prevents Credential Theft**: Unauthorized sites cannot use your Client ID +- **Protects User Data**: Ensures authentication flows only occur on approved domains +- **Compliance Ready**: Meets security standards for production applications +- **Fraud Prevention**: Blocks malicious sites from impersonating your application + +## Web Application Whitelisting + +### Supported URL Formats + +Web3Auth supports various URL formats for comprehensive domain coverage: + +**Standard Domains:** + +``` +https://myapp.com +https://www.myapp.com +https://app.mycompany.com +``` + +**Development Environments:** + +``` +http://localhost:3000 +http://localhost:8080 +https://dev.myapp.com +https://staging.myapp.com +``` + +**Subdomain Patterns:** + +``` +https://*.myapp.com (covers all subdomains) +https://feature-*.myapp.com (wildcard patterns) +``` + +**Port-Specific URLs:** + +``` +https://myapp.com:8443 +http://localhost:3000 +http://127.0.0.1:8080 +``` + +### Adding Web Domains + +1. **Navigate to Project Settings** → **Whitelist** +2. **Click "Add Domain"** or similar button +3. **Enter the complete URL** including protocol (http:// or https://) +4. **Verify the domain** if required +5. **Save the configuration** + +**Best Practices:** + +- Always use HTTPS for production domains +- Include all necessary subdomains +- Add development and staging environments +- Test authentication after adding domains + +## Mobile Application Whitelisting + +### Bundle Identifiers + +For mobile applications, whitelist the app's bundle identifier or package name: + +**iOS Bundle IDs:** + +``` +com.yourcompany.yourapp +com.yourcompany.yourapp.staging +``` + +**Android Package Names:** + +``` +com.yourcompany.yourapp +com.yourcompany.yourapp.debug +``` + +### Deep Link Schemes + +Mobile applications using deep links should whitelist their custom URL schemes: + +**Custom Schemes:** + +``` +yourapp://auth +com.yourcompany.yourapp://callback +``` + +**Universal Links (iOS):** + +``` +https://yourapp.com/auth/callback +``` + +**App Links (Android):** + +``` +https://yourapp.com/auth/callback +``` + +## Environment-Specific Configuration + +### Development Environment + +For development and testing: + +``` +http://localhost:3000 +http://localhost:8080 +http://127.0.0.1:3000 +https://dev.yourapp.com +https://staging.yourapp.com +``` + +**Development Tips:** + +- Whitelist common development ports +- Include both localhost and 127.0.0.1 +- Add staging and testing environments +- Use HTTP for local development (HTTPS for staging) + +### Production Environment + +:::warning Production Requirements + +For Sapphire Mainnet projects, **at least one domain must be whitelisted** before the SDK can be used in production. This is a mandatory security requirement. + +::: + +**Production Checklist:** + +- ✅ All production domains whitelisted +- ✅ HTTPS enforced for all domains +- ✅ Subdomain coverage complete +- ✅ Mobile bundle IDs added +- ✅ Deep link schemes configured +- ✅ Remove development URLs + +## Wildcard Domains + +### Subdomain Wildcards + +Use wildcard patterns to cover multiple subdomains efficiently: + +**Single-level wildcard:** + +``` +https://*.myapp.com +``` + +Covers: `https://api.myapp.com`, `https://admin.myapp.com`, `https://user.myapp.com` + +**Multi-level wildcards:** + +``` +https://*.*.myapp.com +``` + +Covers: `https://api.v1.myapp.com`, `https://admin.staging.myapp.com` + +### Dynamic Subdomains + +For applications with dynamic subdomains (multi-tenant apps): + +``` +https://*.myapp.com +https://tenant-*.myapp.com +https://*.saas.myapp.com +``` + +## Verification Process + +### Domain Verification + +Some domains may require verification to ensure ownership: + +1. **DNS Verification**: Add a TXT record to your domain's DNS +2. **File Upload**: Upload a verification file to your web server +3. **HTML Meta Tag**: Add a meta tag to your website's homepage + +### Verification Status + +Monitor the verification status in your dashboard: + +- ✅ **Verified**: Domain is confirmed and active +- ⏳ **Pending**: Verification in progress +- ❌ **Failed**: Verification unsuccessful, requires attention + +## Common Issues and Solutions + +### Authentication Failures + +**Problem**: Users cannot authenticate on your domain +**Solutions:** + +- Verify the domain is in your whitelist +- Check for typos in the domain name +- Ensure protocol (http/https) matches exactly +- Confirm subdomain patterns are correct + +### Development Environment Issues + +**Problem**: Local development not working +**Solutions:** + +- Add `http://localhost:PORT` to whitelist +- Include `http://127.0.0.1:PORT` as alternative +- Check if your development server uses a different port +- Verify protocol matches (http vs https) + +### Mobile App Issues + +**Problem**: Mobile authentication failing +**Solutions:** + +- Verify bundle ID matches exactly +- Check deep link scheme configuration +- Ensure URL schemes are properly whitelisted +- Test with both debug and release builds + +## Security Best Practices + +### Regular Audits + +- **Monthly Reviews**: Check whitelist for unused domains +- **Remove Stale Entries**: Delete old development or staging URLs +- **Monitor Access**: Review authentication patterns for anomalies +- **Update Documentation**: Keep domain lists current for your team + +### Principle of Least Privilege + +- **Minimal Domains**: Only whitelist necessary domains +- **Specific Patterns**: Avoid overly broad wildcard patterns +- **Environment Separation**: Use different projects for dev/staging/prod +- **Regular Cleanup**: Remove domains when no longer needed + +### Compliance Considerations + +- **Data Residency**: Consider where authentication occurs +- **Privacy Regulations**: Ensure whitelisted domains comply with privacy laws +- **Security Standards**: Meet industry requirements for domain authorization +- **Audit Trails**: Maintain records of domain modifications + +## Advanced Configuration + +### CDN and Load Balancer Support + +For applications using CDNs or load balancers: + +``` +https://cdn.myapp.com +https://lb.myapp.com +https://edge-*.myapp.com +``` + +### Multi-Region Deployments + +For global applications with regional domains: + +``` +https://us.myapp.com +https://eu.myapp.com +https://asia.myapp.com +https://*.global.myapp.com +``` + +### API Gateway Integration + +For applications behind API gateways: + +``` +https://api.myapp.com +https://gateway.myapp.com +https://*.api.myapp.com +``` + +## Next Steps + +- **[Project Settings](./project-settings)** - Configure basic project information +- **[Advanced Project Settings](./advanced/session-management)** - Access advanced configuration options +- **[Session Management](./advanced/session-management)** - Control session duration and behavior diff --git a/ew-sidebar.js b/ew-sidebar.js index 30eabd456e2..e724be4c3e7 100644 --- a/ew-sidebar.js +++ b/ew-sidebar.js @@ -137,6 +137,19 @@ const sidebar = { label: "Configuration", items: [ "dashboard/project-settings", + "dashboard/whitelist", + { + type: "category", + label: "Advanced Settings", + collapsible: true, + collapsed: false, + items: [ + "dashboard/advanced/session-management", + "dashboard/advanced/test-accounts", + "dashboard/advanced/user-details", + "dashboard/advanced/key-export", + ], + }, "dashboard/chains-and-networks", "dashboard/authentication", "dashboard/wallet-services", diff --git a/src/components/EWSDKCards/index.tsx b/src/components/EWSDKCards/index.tsx index 1d59a8370af..266c16a9911 100644 --- a/src/components/EWSDKCards/index.tsx +++ b/src/components/EWSDKCards/index.tsx @@ -50,8 +50,8 @@ export const pnpweb = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -78,8 +78,8 @@ export const pnpweb = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -102,8 +102,8 @@ export const pnpweb = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -143,8 +143,8 @@ export const pnpmobile = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -169,8 +169,8 @@ export const pnpmobile = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -193,8 +193,8 @@ export const pnpmobile = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -217,8 +217,8 @@ export const pnpmobile = ( Quick Start{chevron} - SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron} @@ -261,8 +261,8 @@ export const pnpgaming = (

Unity SDK

- SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron}
@@ -284,8 +284,8 @@ export const pnpgaming = (

Unreal SDK

- SDK Reference{chevron} - Examples{chevron} + SDK Reference{chevron} + Examples{chevron}
diff --git a/src/components/SubNavBar/configs.ts b/src/components/SubNavBar/configs.ts index 8d04f90f891..2e3af048d1d 100644 --- a/src/components/SubNavBar/configs.ts +++ b/src/components/SubNavBar/configs.ts @@ -34,6 +34,16 @@ export const EMBEDDED_WALLETS_SUBNAV_CONFIG: SubNavBarConfig = { label: 'Troubleshooting', path: '/embedded-wallets/troubleshooting/', }, + { + key: 'dashboard', + label: 'Dashboard ↗', + path: 'https://dashboard.web3auth.io/', + }, + { + key: 'demo', + label: 'Demo ↗', + path: 'https://demo.web3auth.io/', + }, ], } diff --git a/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png b/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png index a38269bdbe9..d37087663ec 100644 Binary files a/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png and b/static/img/embedded-wallets/w3a-dashboard/project-settings-advanced.png differ diff --git a/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png b/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png index 493b424d470..b15cf2f0e32 100644 Binary files a/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png and b/static/img/embedded-wallets/w3a-dashboard/project-settings-domain.png differ diff --git a/static/img/embedded-wallets/w3a-dashboard/project-settings-general.png b/static/img/embedded-wallets/w3a-dashboard/project-settings-general.png index ab75e211a84..682b1a8f4b3 100644 Binary files a/static/img/embedded-wallets/w3a-dashboard/project-settings-general.png and b/static/img/embedded-wallets/w3a-dashboard/project-settings-general.png differ diff --git a/static/img/embedded-wallets/w3a-dashboard/test-accounts-settings.png b/static/img/embedded-wallets/w3a-dashboard/test-accounts-settings.png new file mode 100644 index 00000000000..2c5d4fc0a8d Binary files /dev/null and b/static/img/embedded-wallets/w3a-dashboard/test-accounts-settings.png differ