Skip to content

Crystara-Markets/supra-multiwallet

Repository files navigation

Supra Multiwallet Connect Template

A production-ready, open-source multiwallet authentication infrastructure for the Supra blockchain ecosystem. Built with Next.js 14, TypeScript, and modern web standards.

πŸš€ Live Demo β†’
Try the fully-functional demo with Starkey and Ribbit wallet integration

πŸ“– Get Started in 5 Minutes β†’
Complete step-by-step guide with installation, configuration, and integration examples.

πŸ“Έ Preview

Wallet Connection Modal

Beautiful, accessible wallet connection modal with Starkey and Ribbit wallet support

Key Features Shown:

  • 🎨 Modern UI - Clean, gradient-based design with smooth animations
  • πŸ” Secure Authentication - JWT-based auth with signature verification
  • πŸ’Ό Multi-Wallet Support - Seamless integration with Starkey & Ribbit wallets
  • πŸ“± Responsive Design - Works perfectly on mobile, tablet, and desktop
  • ⚑ Edge Runtime Ready - Deploy to Vercel, Cloudflare Workers, and more

🎯 Overview

This template provides a complete, audited solution for integrating multiple wallet providers with JWT-based authentication in your Supra blockchain applications. Copy, customize, and deploy with confidence.

✨ Features

πŸ”Œ Wallet Support

  • Starkey Wallet - Full integration with connection, signing, and account management
  • Ribbit Wallet - Complete support for Supra's primary wallet providers
  • Unified Interface - Consistent API across different wallet providers
  • WalletConnect Modal - Beautiful, accessible wallet selection UI

πŸ” Authentication & Security

  • JWT Authentication - Industry-standard token-based auth with Edge Runtime support
  • Protected Routes - Easy-to-use route protection based on wallet connection
  • HttpOnly Cookies - Secure token storage preventing XSS attacks
  • Wallet Signature Verification - Cryptographic proof of wallet ownership
  • Nonce-based Security - Prevention of replay attacks
  • Production-Ready - Audited security patterns used in live NFT marketplace

🎨 UI/UX

  • Modern Design System - Clean, consistent, and accessible components
  • Responsive Layout - Optimized for mobile, tablet, and desktop
  • Framer Motion Animations - Smooth, professional interactions
  • Shadcn UI Components - High-quality primitives
  • Navbar Integration - Drop-in wallet connection UI
  • Toast Notifications - User-friendly feedback system

πŸ—οΈ Developer Experience

  • TypeScript - Full type safety across the application
  • Edge Runtime Compatible - Deploy to Vercel, Cloudflare Workers, etc.
  • Clear Code Structure - Easy to understand and modify
  • Comprehensive Examples - Working implementations of all features
  • No Hidden Dependencies - Everything is transparent and auditable

πŸš€ Quick Start

# Clone the repository
git clone https://github.com/yourusername/supra-multiwallet.git

# Install dependencies
npm install

# Run development server
npm run dev

Open http://localhost:3000 to see the demo application.

πŸ“‹ Environment Variables

Create a .env.local file in the root directory:

# Required - JWT Secret (MUST be 64+ characters for production security)
JWT_SECRET=your-super-secret-jwt-key-that-is-at-least-64-characters-long-for-security

# Required - Application URL
NEXT_PUBLIC_APP_URL=http://localhost:3000

# Required - Supra Chain ID (6 = testnet, 8 = mainnet)
NEXT_PUBLIC_SUPRA_CHAIN_ID=6

# Optional - Node Environment (automatically set by hosting platforms)
NODE_ENV=development

πŸ” Generating a Secure JWT_SECRET

CRITICAL: Your JWT_SECRET must be:

  • At least 64 characters (longer is better)
  • Cryptographically random
  • Never committed to git
  • Different for each environment (dev, staging, production)

Generate a secure secret using one of these methods:

# Using Node.js
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"

# Using OpenSSL
openssl rand -hex 64

# Using PowerShell (Windows)
[Convert]::ToBase64String((1..64 | ForEach-Object { Get-Random -Minimum 0 -Maximum 256 }))

πŸ“ Project Structure

supra-multiwallet/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/auth/                    # Authentication API endpoints
β”‚   β”‚   β”œβ”€β”€ check/                   # Verify authentication status
β”‚   β”‚   β”œβ”€β”€ create-jwt/              # Create JWT after signature verification
β”‚   β”‚   β”œβ”€β”€ nonce/                   # Generate time-based nonces
β”‚   β”‚   β”œβ”€β”€ wallet-login/            # Set httpOnly cookie
β”‚   β”‚   └── wallet-logout/           # Clear authentication
β”‚   β”œβ”€β”€ protected/[walletAddress]/   # Example protected dynamic route
β”‚   β”‚   β”œβ”€β”€ page.tsx                 # Server-side auth verification
β”‚   β”‚   └── client.tsx               # Client-side protected content
β”‚   β”œβ”€β”€ layout.tsx                   # Root layout with providers
β”‚   └── page.tsx                     # Landing page with demo
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ ConnectWalletHandler.tsx     # Wallet connection logic wrapper
β”‚   β”œβ”€β”€ Navbar.tsx                   # Navigation with wallet integration
β”‚   β”œβ”€β”€ SendSupraTokens.tsx          # Token transfer demo component
β”‚   β”œβ”€β”€ WalletProvider.tsx           # Wallet context provider
β”‚   └── ui/                          # Shadcn UI primitives
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ useSupraMultiWallet.ts       # Main multiwallet hook (Starkey & Ribbit)
β”‚   └── useConversionUtils.ts        # Blockchain utility functions
β”œβ”€β”€ lib/
β”‚   └── auth.ts                      # JWT, nonce, signature verification
β”œβ”€β”€ docs/
β”‚   └── QUICK_START.md               # Step-by-step setup guide
└── public/                          # Static assets

πŸ”§ Core Components

Wallet Provider

Wrap your application to enable wallet functionality:

<WalletProvider>
  {/* Your app */}
</WalletProvider>

Connect Button

Pre-built wallet connection UI:

import { WalletConnectButton } from '@/components/WalletConnectButton'

<WalletConnectButton />

Protected Routes

Server-side authentication for wallet-specific pages:

// app/protected/[walletAddress]/page.tsx
import { cookies } from 'next/headers';
import { verifyToken } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function ProtectedPage({ params }: { params: { walletAddress: string } }) {
  const token = cookies().get('authToken')?.value;
  const verified = await verifyToken(token);
  
  // Redirect if not authenticated
  if (!verified) {
    return <div>Unauthorized, requires sign-in to wallet to access this page.</div>;
  }
  
  // Verify wallet address matches
  if (verified.address.toLowerCase() !== params.walletAddress.toLowerCase()) {
    return <div>Unauthorized, requires sign-in to wallet to access this page.</div>;
  }
  
  return <div>Protected content for {verified.address}</div>;
}

πŸ” Security Architecture

Authentication Flow

  1. User clicks "Connect Wallet"
  2. Wallet provider injected script detected
  3. User approves connection in wallet
  4. Backend generates unique cryptographic nonce (32 bytes)
  5. User signs nonce + message with wallet
  6. Backend verifies signature cryptographically
  7. JWT token issued in HttpOnly cookie
  8. Subsequent requests authenticated via cookie

Security Features

  • βœ… HttpOnly Cookies - Tokens inaccessible to JavaScript, preventing XSS
  • βœ… Secure Flag - HTTPS-only in production
  • βœ… SameSite: Lax - CSRF protection
  • βœ… 24h Expiration - Tokens auto-expire appropriately
  • βœ… Cryptographic Nonce - 32-byte random nonces via Web Crypto API
  • βœ… Ed25519 Signature Verification - Wallet ownership proof via nacl
  • βœ… Edge Runtime Compatible - Serverless deployment ready
  • βœ… Jose (JWT) - Industry-standard JWT library

πŸ” Security Audit Results

Last Audited: October 2024

βœ… Implemented Security Features:

  • HttpOnly cookie storage
  • Secure flag on production
  • SameSite CSRF protection
  • Cryptographic nonce generation
  • Token expiration (24h)
  • Edge runtime compatibility

βœ… Security Features Implemented:

  1. βœ… Signature Verification

    • Location: lib/auth.ts - verifyWalletSignature()
    • Implementation: Ed25519 cryptographic signature verification using nacl
    • Security: Proves wallet ownership before issuing JWT
    • Status: βœ… Implemented and tested
  2. βœ… Time-Based Nonce Validation

    • Location: lib/auth.ts - createNonce() and validateNonce()
    • Implementation: Cryptographically signed, time-based nonces (5-minute expiry)
    • Security: Prevents replay attacks without requiring external storage
    • Upgrade path: Can add KV storage for zero replay window if needed
    • Status: βœ… Implemented and tested
  3. ⚠️ Client-side Token Storage

    • Location: hooks/useSupraMultiWallet.ts:937-942
    • Issue: Legacy code attempts to store token in localStorage
    • Impact: Minor - server-side httpOnly cookie is the source of truth
    • Status: Should be removed in cleanup (non-critical)

πŸ“ Optional Enhancements (PR Welcome!):

Potential security improvements for advanced use cases:

  • Upgrading to KV storage for zero replay window (optional)
  • Rate limiting on auth endpoints (recommended)
  • Token refresh pattern (nice-to-have)
  • JWT revocation capability (for advanced use cases)
  • Address derivation verification (when Supra SDK provides it)

Why Client-Side Wallet Signing is Necessary

The authentication flow requires client-side wallet interactions because:

  • Wallet extensions inject into browser - Only accessible client-side
  • User must approve in wallet UI - Cannot be done server-side
  • Private keys never leave wallet - Signatures prove ownership without exposing keys
  • Standard Web3 pattern - Used by OpenSea, Uniswap, etc.

The security model is:

  1. Challenge-response authentication - Server generates nonce
  2. Cryptographic proof - User signs with private key
  3. Server verification - Server validates signature matches address
  4. Secure token issuance - JWT stored in httpOnly cookie

This is secure when properly implemented (with signature verification).

🎨 Customization

Styling

This template uses Tailwind CSS with a custom design system. Colors, spacing, and typography can be customized in tailwind.config.ts.

Adding More Wallets

The architecture supports adding additional wallet providers. See CONTRIBUTING.md for guidelines.

Environment Variables

# Required
NEXT_PUBLIC_APP_URL=http://localhost:3000
JWT_SECRET=your-secret-key-here

# Optional
NEXT_PUBLIC_NETWORK=testnet

🀝 Contributing

This is an open-source community project! Contributions are welcome:

  • πŸ› Bug reports and fixes
  • ✨ Feature requests and implementations
  • πŸ“ Documentation improvements
  • πŸ” Security audits and recommendations (especially needed!)
  • 🌐 Additional wallet integrations

High Priority Contributions Needed:

  1. Security testing and penetration testing
  2. Rate limiting implementation for auth endpoints
  3. Additional wallet integrations (as Supra ecosystem grows)
  4. Documentation improvements and tutorials

Future SDK

Once patterns stabilize and the community validates the approach, we plan to release an NPM package for even easier integration. Interested in helping? Open an issue!

πŸ“‹ Roadmap

βœ… Completed

  • Starkey wallet integration
  • Ribbit wallet integration
  • JWT authentication system with httpOnly cookies
  • Signature verification (Ed25519 with nacl)
  • Time-based nonce validation (zero dependencies)
  • Protected routes with SSR auth verification
  • Dynamic protected routes (/protected/[walletAddress])
  • Example UI components (Navbar, SendTokens)
  • Wallet balance display
  • Transaction signing examples (send tokens)
  • Modern responsive UI with Framer Motion

🚧 In Progress / Planned

  • Rate limiting for auth endpoints (recommended)
  • Token refresh pattern (optional)
  • Additional wallet providers (as ecosystem grows)
  • Multi-chain support
  • NPM package/SDK
  • Comprehensive test suite

πŸ“„ License

MIT License - feel free to use in your projects!

πŸ™ Acknowledgments

Built with love for the Supra blockchain ecosystem. Based on production code from [Your NFT Marketplace].

Security Contributors: (Your name here - PR to fix security issues!)

πŸ“ž Support

  • Open an issue for bugs or questions
  • PR welcome for improvements
  • Security issues: Please email security@[yourdomain] or open a private security advisory
  • Star the repo if this helped you!

⚠️ Important Security Notice

This is a production-ready template with implemented security features. However, every application has unique security requirements.

βœ… Security Features Implemented:

  1. βœ… Ed25519 signature verification
  2. βœ… Time-based nonce validation (5-minute window)
  3. βœ… HttpOnly cookie storage
  4. βœ… CSRF protection (SameSite)
  5. βœ… Token expiration (24h)

πŸ“‹ Before Production Deployment:

  • Generate a secure JWT_SECRET (64+ characters)
  • Review docs/SECURITY_IMPLEMENTATION.md
  • Test authentication flow thoroughly
  • Consider adding rate limiting (recommended)
  • Enable HTTPS (required for Secure cookies)
  • Review logs and error handling
  • Understand the 5-minute nonce replay window (or upgrade to KV)

πŸ”’ Security Disclaimer: While this implementation follows security best practices and has been audited:

  • Conduct your own security review for your specific use case
  • Test thoroughly in staging before production
  • Monitor for suspicious activity
  • Keep dependencies updated (npm audit)
  • Follow OWASP guidelines

See docs/SECURITY_IMPLEMENTATION.md for detailed security analysis and threat model.

Use at your own risk. Contributors provide this as-is without warranty.

About

Multi-wallet connector for Supra blockchain

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published