Higienização de entradas e prevenção de injeções
Defenda aplicativos de borda contra XSS, injeção de SQL e ataques relacionados higienizando as entradas e codificando corretamente as saídas.
Higienização de entradas e prevenção de injeções é uma aula grátis de Edge Computing with Cloudflare Workers & Deno no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Edge Computing with Cloudflare Workers & Deno, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Edge Computing with Cloudflare Workers & Deno inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}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 rowValidate 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.
Perguntas Frequentes
A aula “Higienização de entradas e prevenção de injeções” é grátis?
Sim — o texto completo de “Higienização de entradas e prevenção de injeções” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Edge Computing with Cloudflare Workers & Deno, atualize para CoddyKit PRO. O curso de Edge Computing with Cloudflare Workers & Deno inclui 4 aulas no total.
O que vou aprender em “Higienização de entradas e prevenção de injeções”?
Defenda aplicativos de borda contra XSS, injeção de SQL e ataques relacionados higienizando as entradas e codificando corretamente as saídas. Você pratica Edge Computing with Cloudflare Workers & Deno com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Edge Computing with Cloudflare Workers & Deno?
Nenhuma experiência prévia é necessária. Edge Computing with Cloudflare Workers & Deno no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Higienização de entradas e prevenção de injeções”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Edge Computing with Cloudflare Workers & Deno?
Sim. Cada aula de Edge Computing with Cloudflare Workers & Deno inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Autenticação e autorização
- Limitação de taxa e proteção contra DDoS
- Gerenciamento seguro de segredos
- Higienização de entradas e prevenção de injeções