Sobes.tech
Middle

How can you secure an application from potentially dangerous client-side input?

sobes.tech AI

Answer from AI

To protect against dangerous input:

  1. Data sanitization: Clean user input from potentially malicious code (HTML, JavaScript) before displaying it on the page.

    // Example of sanitization using DOMPurify
    const cleanHtml = DOMPurify.sanitize(userInput);
    
  2. Output escaping: Convert special characters to their safe equivalents before displaying on the page to prevent code execution.

    <!-- Example of escaping -->
    <p id="output"></p>
    <script>
      const userInput = "<script>alert('XSS')</script>";
      document.getElementById('output').textContent = userInput; // Using textContent for safe output
    </script>
    
  3. Content Security Policy (CSP): Configure the Content-Security-Policy HTTP header to restrict content sources that can be loaded and executed by the browser.

    Content-Security-Policy: default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline';
    
  4. Data validation: Check user input for compliance with expected format, data type, and length both on the client and server.

    // Example of client-side validation
    if (inputField.value.length > 100) {
      // Validation error
    }
    
  5. Use of secure APIs and libraries: Prefer built-in APIs and reputable libraries for DOM manipulation, data processing, and prevent direct use of innerHTML with unsanitized data.

  6. User privilege restriction: Apply the principle of least privilege, where the user interface does not allow potentially dangerous actions without proper authorization.

  7. HTTPS: Always use HTTPS to encrypt data between the client and server.

  8. Protection against CSRF (Cross-Site Request Forgery): Use CSRF tokens to verify the authenticity of requests sent from the client.

    // Example of sending a CSRF token
    fetch('/api/update', {
      method: 'POST',
      headers: {
        'X-CSRF-Token': csrfToken
      },
      body: JSON.stringify(data)
    });
    
  9. HttpOnly flag for cookies: Set the HttpOnly flag for session cookies to prevent access via JavaScript.

  10. Regular updates of dependencies: Keep used libraries and frameworks up to date to fix known vulnerabilities.