输入清理与注入防护
通过正确清理输入和编码输出,保护边缘应用免受 XSS、SQL 注入及相关攻击。
输入清理与注入防护 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「输入清理与注入防护」课时是免费的吗?
是的 — 「输入清理与注入防护」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
「输入清理与注入防护」这节课中我会学到什么?
通过正确清理输入和编码输出,保护边缘应用免受 XSS、SQL 注入及相关攻击。 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「输入清理与注入防护」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?
能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 身份验证与授权
- 速率限制与 DDoS 防护
- 安全的机密信息管理
- 输入清理与注入防护