All files / security WalletSecurity.js

0% Statements 0/90
0% Branches 0/45
0% Functions 0/13
0% Lines 0/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * Wallet Connection Security
 * Prevents fake wallets, ensures safe connections
 */
 
const ethers = require('ethers');
 
class WalletSecurity {
  constructor() {
    // Supported wallet types
    this.supportedWallets = new Set([
      'metamask',
      'walletconnect',
      'coinbase',
      'trust',
      'rainbow',
      'ledger',
      'trezor',
    ]);
    
    // Verified wallet providers
    this.verifiedProviders = new Map();
  }
 
  /**
   * Verify wallet connection is legitimate
   * PREVENTS: Fake wallet exploits
   */
  async verifyWalletConnection(provider, address) {
    console.log(`🔐 Verifying wallet connection: ${address}`);
    
    const checks = [];
    
    // Check 1: Valid address format
    try {
      if (!ethers.utils.isAddress(address)) {
        checks.push({
          name: 'Address Format',
          passed: false,
          reason: 'Invalid address format',
        });
        return { valid: false, checks };
      }
      checks.push({ name: 'Address Format', passed: true });
    } catch (error) {
      checks.push({ name: 'Address Format', passed: false, reason: error.message });
      return { valid: false, checks };
    }
    
    // Check 2: Provider is legitimate
    const providerCheck = this.verifyProvider(provider);
    checks.push({
      name: 'Provider Verification',
      passed: providerCheck.valid,
      reason: providerCheck.reason,
    });
    
    // Check 3: Address owns private key (signature test)
    try {
      const message = `Verify ownership: ${Date.now()}`;
      const signature = await provider.request({
        method: 'personal_sign',
        params: [message, address],
      });
      
      const recovered = ethers.utils.verifyMessage(message, signature);
      const ownsKey = recovered.toLowerCase() === address.toLowerCase();
      
      checks.push({
        name: 'Private Key Ownership',
        passed: ownsKey,
        reason: ownsKey ? 'Signature verified' : 'Signature mismatch',
      });
      
      if (!ownsKey) {
        return { valid: false, checks };
      }
    } catch (error) {
      checks.push({
        name: 'Private Key Ownership',
        passed: false,
        reason: error.message,
      });
      return { valid: false, checks };
    }
    
    // Check 4: Not a contract address (users should use EOAs)
    try {
      const code = await provider.request({
        method: 'eth_getCode',
        params: [address, 'latest'],
      });
      
      const isContract = code && code !== '0x' && code !== '0x0';
      checks.push({
        name: 'EOA Check',
        passed: !isContract,
        warning: isContract ? 'Contract wallets require extra verification' : null,
      });
    } catch (error) {
      // If check fails, allow but warn
      checks.push({
        name: 'EOA Check',
        passed: true,
        warning: 'Could not verify - proceeding with caution',
      });
    }
    
    // Check 5: Address not on blacklist
    // (Handled by SecurityMonitor)
    
    // All checks passed
    const allPassed = checks.every(c => c.passed);
    
    return {
      valid: allPassed,
      checks,
      warnings: checks.filter(c => c.warning).map(c => c.warning),
    };
  }
 
  /**
   * Verify provider is legitimate (not fake wallet)
   */
  verifyProvider(provider) {
    // Check 1: Has required methods
    const requiredMethods = ['request', 'on', 'removeListener'];
    for (const method of requiredMethods) {
      if (typeof provider[method] !== 'function') {
        return {
          valid: false,
          reason: `Missing required method: ${method}`,
        };
      }
    }
    
    // Check 2: Has valid chainId
    if (!provider.chainId) {
      return {
        valid: false,
        reason: 'No chainId provided',
      };
    }
    
    // Check 3: Recognized provider type
    const providerName = this.identifyProvider(provider);
    if (!providerName) {
      return {
        valid: false,
        reason: 'Unknown provider type',
      };
    }
    
    return {
      valid: true,
      providerName,
    };
  }
 
  /**
   * Identify wallet provider
   */
  identifyProvider(provider) {
    if (provider.isMetaMask) return 'metamask';
    if (provider.isCoinbaseWallet) return 'coinbase';
    if (provider.isTrust) return 'trust';
    if (provider.isWalletConnect) return 'walletconnect';
    if (provider.isRainbow) return 'rainbow';
    
    return null;
  }
 
  /**
   * Secure wallet connection flow
   */
  async connectWallet(provider) {
    try {
      // Request accounts
      const accounts = await provider.request({
        method: 'eth_requestAccounts',
      });
      
      if (!accounts || accounts.length === 0) {
        throw new Error('No accounts returned');
      }
      
      const address = accounts[0];
      
      // Verify connection
      const verification = await this.verifyWalletConnection(provider, address);
      
      if (!verification.valid) {
        throw new Error('Wallet verification failed');
      }
      
      // Get chain ID
      const chainId = await provider.request({ method: 'eth_chainId' });
      
      // Store connection
      this.verifiedProviders.set(address, {
        provider,
        address,
        chainId,
        connectedAt: Date.now(),
        verified: true,
      });
      
      return {
        success: true,
        address,
        chainId,
        provider: this.identifyProvider(provider),
        warnings: verification.warnings,
      };
    } catch (error) {
      console.error('Wallet connection error:', error);
      return {
        success: false,
        error: error.message,
      };
    }
  }
 
  /**
   * Disconnect wallet
   */
  disconnectWallet(address) {
    this.verifiedProviders.delete(address);
  }
 
  /**
   * Check if wallet is connected
   */
  isConnected(address) {
    return this.verifiedProviders.has(address);
  }
 
  /**
   * Get connection details
   */
  getConnection(address) {
    return this.verifiedProviders.get(address);
  }
 
  /**
   * Validate transaction signature
   * PREVENTS: Unauthorized transactions
   */
  async validateTransactionSignature(tx, signature, address) {
    try {
      // Reconstruct transaction hash
      const txHash = ethers.utils.keccak256(
        ethers.utils.defaultAbiCoder.encode(
          ['address', 'uint256', 'string'],
          [tx.to, tx.value, tx.data]
        )
      );
      
      // Verify signature
      const recovered = ethers.utils.recoverAddress(txHash, signature);
      
      return recovered.toLowerCase() === address.toLowerCase();
    } catch (error) {
      console.error('Signature validation error:', error);
      return false;
    }
  }
 
  /**
   * Prevent common wallet exploits
   */
  checkForExploits(transaction) {
    const exploits = [];
    
    // Check 1: Infinite approval (common exploit)
    if (transaction.method === 'approve') {
      const MAX_UINT256 = ethers.constants.MaxUint256;
      if (transaction.params.amount.eq(MAX_UINT256)) {
        exploits.push({
          type: 'INFINITE_APPROVAL',
          severity: 'HIGH',
          message: 'Infinite token approval detected',
          recommendation: 'Approve only required amount',
        });
      }
    }
    
    // Check 2: Unusual gas price (could indicate MEV attack)
    if (transaction.gasPrice) {
      const gasPrice = ethers.BigNumber.from(transaction.gasPrice);
      const gwei = gasPrice.div(1e9);
      
      if (gwei.gt(1000)) { // > 1000 GWEI
        exploits.push({
          type: 'HIGH_GAS_PRICE',
          severity: 'MEDIUM',
          message: `Unusually high gas price: ${gwei} GWEI`,
          recommendation: 'Check if this is intentional',
        });
      }
    }
    
    // Check 3: Transferring to new address (phishing risk)
    if (transaction.method === 'transfer' && transaction.to) {
      // Check if address is new/unverified
      // (In production, check against known addresses)
    }
    
    return exploits;
  }
}
 
module.exports = new WalletSecurity();