0Pricing
Edge Computing with Cloudflare Workers & Deno · Lección

Saneamiento de entradas y prevención de inyecciones

Defienda las aplicaciones edge frente a XSS, inyección SQL y ataques relacionados saneando las entradas y codificando correctamente las salidas.

Saneamiento de entradas y prevención de inyecciones es una lección gratuita de Edge Computing with Cloudflare Workers & Deno en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Edge Computing with Cloudflare Workers & Deno, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Sanitization Matters

Even at the edge, untrusted input is the root of most attacks. Sanitization and proper output encoding stop:

  • Cross-Site Scripting (XSS)
  • SQL / query injection
  • Header and log injection

Validation checks shape, sanitization makes input safe to use.

Understanding XSS

XSS happens when attacker-controlled data is rendered as HTML and executes as script.

If a Worker echoes user input into a page without encoding, an attacker can inject scripts.

// Dangerous: user input goes straight into HTML
const html = '<div>' + userInput + '</div>';

Output Encoding for HTML

The fix for XSS is context-aware output encoding. Escape HTML-special characters before rendering.

function escapeHtml(s) {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

Preventing SQL Injection

Never build SQL by string concatenation. Use parameterized queries, the D1 and Deno drivers bind values safely.

// Safe: bound parameter, never concatenated
const { results } = await env.DB
  .prepare('SELECT * FROM users WHERE email = ?')
  .bind(email)
  .all();

The Danger of Concatenation

Concatenated SQL lets an attacker break out of the intended query.

// NEVER do this
const sql = "SELECT * FROM users WHERE email = '" + email + "'";
// email = "' OR '1'='1" returns every row

Validate Then Sanitize

Combine both defenses: validate that input matches an expected pattern, then sanitize for the context it is used in.

const emailRe = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
if (!emailRe.test(email)) {
  return new Response('Invalid email', { status: 400 });
}

Header & Redirect Injection

User input placed into response headers or redirect URLs can inject newlines or open redirects.

  • Strip CR/LF from header values
  • Allowlist redirect destinations
const clean = value.replace(/[\r\n]/g, '');
headers.set('X-User-Tag', clean);

Content Security Policy

A CSP header is a strong second line of defense against XSS, it restricts what scripts may run.

headers.set(
  'Content-Security-Policy',
  "default-src 'self'; script-src 'self'"
);

Sanitizing Rich HTML

When you must accept HTML (e.g. user comments), use a vetted sanitizer library rather than regex, allowlist safe tags and attributes.

import DOMPurify from 'isomorphic-dompurify';
const safe = DOMPurify.sanitize(userHtml);

Defense in Depth

No single control is enough. Layer defenses:

  • Validate input shape
  • Use parameterized queries
  • Encode output per context
  • Set CSP and security headers

If one layer fails, the others still protect you.

Best Practices Summary

To keep edge apps safe:

  • Treat all input as hostile
  • Never concatenate SQL or HTML with raw input
  • Encode for the exact output context
  • Add CSP and strip control characters from headers

Quick Check

What is the most reliable way to prevent SQL injection in a D1 query?

Recap

You hardened your app against injection:

  • Encode output to stop XSS
  • Use parameterized queries to stop SQL injection
  • Strip control characters and allowlist redirects
  • Add CSP and sanitize rich HTML with a trusted library

Defense in depth keeps edge applications resilient even when one layer slips.

Preguntas frecuentes

¿La lección «Saneamiento de entradas y prevención de inyecciones» es gratis?

Sí — el texto completo de «Saneamiento de entradas y prevención de inyecciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Edge Computing with Cloudflare Workers & Deno, actualiza a CoddyKit PRO. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.

¿Qué aprenderé en «Saneamiento de entradas y prevención de inyecciones»?

Defienda las aplicaciones edge frente a XSS, inyección SQL y ataques relacionados saneando las entradas y codificando correctamente las salidas. Practicas Edge Computing with Cloudflare Workers & Deno con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Edge Computing with Cloudflare Workers & Deno?

No se requiere experiencia previa. Edge Computing with Cloudflare Workers & Deno en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Saneamiento de entradas y prevención de inyecciones»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Edge Computing with Cloudflare Workers & Deno?

Sí. Cada lección de Edge Computing with Cloudflare Workers & Deno incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Autenticación y autorización
  2. Limitación de tasa y protección contra DDoS
  3. Gestión segura de secretos
  4. Saneamiento de entradas y prevención de inyecciones
← Volver a Edge Computing with Cloudflare Workers & Deno