XSS 與 CSP
XSS 類型
| 類型 | 說明 | 範例 |
|------|------|------|
| Reflected XSS | 參數直接渲染到頁面 | ?q=<script>alert(1)</script> |
| Stored XSS | 儲存到資料庫後顯示 | 留言板張貼惡意腳本 |
| DOM-based XSS | 前端 JavaScript 動態插入 | innerHTML = userInput |
Vibe Prompt
「幫我在 Next.js 中實作 CSP (Content Security Policy) Header,防止 XSS 攻擊。」
// next.config.js
const csp = {
"default-src": ["'self'"],
"script-src": ["'self'", "'unsafe-inline'", "https://pagead2.googlesyndication.com"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "https:", "data:"],
"font-src": ["'self'"],
"connect-src": ["'self'", "https://*.supabase.co"],
}
const cspString = Object.entries(csp)
.map(([key, vals]) => `${key} ${vals.join(' ')}`)
.join('; ')
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{ key: 'Content-Security-Policy', value: cspString },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
],
},
]
},
}