Labs ICT
Pro Login

Security Basics

Cross-Site Scripting (XSS)

XSS is one of the most common web security vulnerabilities. It happens when user input is inserted into the page without proper sanitization, allowing attackers to inject malicious scripts.

// ❌ Dangerous — never trust user input
element.innerHTML = userInput;

// ✅ Safe — use textContent for plain text
element.textContent = userInput;

// ✅ If you must use HTML, sanitize it first
function sanitize(html) {
  const div = document.createElement("div");
  div.textContent = html;
  return div.innerHTML;
}

Cross-Site Request Forgery (CSRF)

CSRF tricks a logged-in user into making unintended requests. Always use CSRF tokens in forms and verify them on the server.

// Include CSRF token in fetch requests
async function safePost(url, data) {
  const token = document.querySelector('meta[name="csrf-token"]').content;

  return fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-Token": token,
    },
    body: JSON.stringify(data),
  });
}

Input Validation

Always validate and sanitize user input on both client and server side. Never rely solely on client-side validation.

function validateEmail(email) {
  const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!pattern.test(email)) {
    throw new Error("Invalid email format");
  }
  return email.toLowerCase().trim();
}

function sanitizeInput(input) {
  return input
    .replace(/&/g, "&")
    .replace(//g, ">")
    .replace(/"/g, """)
    .replace(/'/g, "'");
Try it Yourself →

Content Security Policy (CSP)

CSP is a browser mechanism that restricts which resources can be loaded. Set it via HTTP headers to prevent unauthorized scripts from running.

// CSP header (set on the server):
// Content-Security-Policy: default-src 'self'; script-src 'self'

// This blocks inline scripts and external sources
// <script>alert('xss')</script> — blocked!
// <script src="evil.com/hack.js"></script> — blocked!

Secure Communication

Always use HTTPS in production. Never store sensitive data in localStorage — use httpOnly cookies instead. Don't log sensitive information like passwords or tokens.

// ❌ Don't do this
localStorage.setItem("token", authToken);

// ✅ Let the server handle secure cookies
// The server sets: Set-Cookie: token=...; HttpOnly; Secure; SameSite=Strict

// ❌ Don't log sensitive data
console.log("User password:", password);

// ✅ Log only what's needed
console.log("User logged in:", username);

Summary

Web security is about defense in depth. Sanitize input, validate on both sides, use CSP, and never store secrets in the browser. Security isn't optional — it's a requirement.