入力サニタイズとインジェクション対策
入力をサニタイズし出力を正しくエンコードすることで、XSS、SQLインジェクションなどの攻撃からエッジアプリケーションを守ります。
「入力サニタイズとインジェクション対策」はCoddyKit上の無料Edge Computing with Cloudflare Workers & Denoレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「入力サニタイズとインジェクション対策」レッスンは無料ですか?
はい。「入力サニタイズとインジェクション対策」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Edge Computing with Cloudflare Workers & Denoコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。
「入力サニタイズとインジェクション対策」で何を学びますか?
入力をサニタイズし出力を正しくエンコードすることで、XSS、SQLインジェクションなどの攻撃からエッジアプリケーションを守ります。 ブラウザで直接実行するハンズオンコードでEdge Computing with Cloudflare Workers & Denoを演習し、24時間対応の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対策
- 安全なシークレット管理
- 入力サニタイズとインジェクション対策