Skip to main content 홈 크리에이터 loulanyue awesome-claude-notes security-review
security-review Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist and patterns.
설치로 이동 Skills Marketplace 커뮤니티가 만든 AI 스킬을 발견하고 탐색하세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/loulanyue/awesome-claude-notes --skill security-review명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
Zip 다운로드 다운로드 중... cloud-infrastructure-security.md 9.5 KB name security-review description Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist and patterns. source_path skills/security-review/SKILL.md
安全性審查技能
此技能確保所有程式碼遵循安全性最佳實務並識別潛在漏洞。
何時啟用
實作認證或授權
處理使用者輸入或檔案上傳
建立新的 API 端點
處理密鑰或憑證
實作支付功能
儲存或傳輸敏感資料
整合第三方 API
安全性檢查清單
1. 密鑰管理
❌ 絕不這樣做
const apiKey = "sk-proj-xxxxx"
const dbPassword = "password123"
✅ 總是這樣做
const apiKey = process.env .OPENAI_API_KEY
const dbUrl = process.env .DATABASE_URL
if (!apiKey) {
throw new Error ('OPENAI_API_KEY not configured' )
}
驗證步驟
無寫死的 API 金鑰、Token 或密碼
所有密鑰在環境變數中
.env.local 在 .gitignore 中
git 歷史中無密鑰
生產密鑰在託管平台(Vercel、Railway)中
2. 輸入驗證
總是驗證使用者輸入 import { z } from 'zod'
const CreateUserSchema = z.object ({
email : z.string ().email (),
name : z.string ().min (1 ).max (100 ),
age : z.number ().int ().min (0 ).max (150 )
})
export async function createUser (input : unknown ) {
try {
const validated = CreateUserSchema .parse (input)
return await db.users .create (validated)
} catch (error) {
if (error instanceof z.ZodError ) {
return { success : false , errors : error.errors }
}
throw error
}
}
檔案上傳驗證 function validateFileUpload (file : File ) {
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error ('File too large (max 5MB)' )
}
const allowedTypes = ['image/jpeg' , 'image/png' , 'image/gif' ]
if (!allowedTypes.includes (file.type )) {
throw new Error ('Invalid file type' )
}
const allowedExtensions = ['.jpg' , '.jpeg' , '.png' , '.gif' ]
const extension = file.name .toLowerCase ().match (/\.[^.]+$/ )?.[0 ]
if (!extension || !allowedExtensions.includes (extension)) {
throw new Error ('Invalid file extension' )
}
return true
}
驗證步驟
3. SQL 注入預防
❌ 絕不串接 SQL
const query = `SELECT * FROM users WHERE email = '${userEmail} '`
await db.query (query)
✅ 總是使用參數化查詢
const { data } = await supabase
.from ('users' )
.select ('*' )
.eq ('email' , userEmail)
await db.query (
'SELECT * FROM users WHERE email = $1' ,
[userEmail]
)
驗證步驟
4. 認證與授權
JWT Token 處理
localStorage .setItem ('token' , token)
res.setHeader ('Set-Cookie' ,
`token=${token} ; HttpOnly; Secure; SameSite=Strict; Max-Age=3600` )
授權檢查 export async function deleteUser (userId : string , requesterId : string ) {
const requester = await db.users .findUnique ({
where : { id : requesterId }
})
if (requester.role !== 'admin' ) {
return NextResponse .json (
{ error : 'Unauthorized' },
{ status : 403 }
)
}
await db.users .delete ({ where : { id : userId } })
}
Row Level Security(Supabase)
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users view own data"
ON users FOR SELECT
USING (auth.uid() = id);
CREATE POLICY "Users update own data"
ON users FOR UPDATE
USING (auth.uid() = id);
驗證步驟
5. XSS 預防
淨化 HTML import DOMPurify from 'isomorphic-dompurify'
function renderUserContent (html : string ) {
const clean = DOMPurify .sanitize (html, {
ALLOWED_TAGS : ['b' , 'i' , 'em' , 'strong' , 'p' ],
ALLOWED_ATTR : []
})
return <div dangerouslySetInnerHTML ={{ __html: clean }} />
}
Content Security Policy
const securityHeaders = [
{
key : 'Content-Security-Policy' ,
value : `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
` .replace (/\s{2,}/g , ' ' ).trim ()
}
]
驗證步驟
6. CSRF 保護
CSRF Tokens import { csrf } from '@/lib/csrf'
export async function POST (request : Request ) {
const token = request.headers .get ('X-CSRF-Token' )
if (!csrf.verify (token)) {
return NextResponse .json (
{ error : 'Invalid CSRF token' },
{ status : 403 }
)
}
}
SameSite Cookies res.setHeader ('Set-Cookie' ,
`session=${sessionId} ; HttpOnly; Secure; SameSite=Strict` )
驗證步驟
7. 速率限制
API 速率限制 import rateLimit from 'express-rate-limit'
const limiter = rateLimit ({
windowMs : 15 * 60 * 1000 ,
max : 100 ,
message : 'Too many requests'
})
app.use ('/api/' , limiter)
昂貴操作
const searchLimiter = rateLimit ({
windowMs : 60 * 1000 ,
max : 10 ,
message : 'Too many search requests'
})
app.use ('/api/search' , searchLimiter)
驗證步驟
8. 敏感資料暴露
日誌記錄
console .log ('User login:' , { email, password })
console .log ('Payment:' , { cardNumber, cvv })
console .log ('User login:' , { email, userId })
console .log ('Payment:' , { last4 : card.last4 , userId })
錯誤訊息
catch (error) {
return NextResponse .json (
{ error : error.message , stack : error.stack },
{ status : 500 }
)
}
catch (error) {
console .error ('Internal error:' , error)
return NextResponse .json (
{ error : 'An error occurred. Please try again.' },
{ status : 500 }
)
}
驗證步驟
9. 區塊鏈安全(Solana)
錢包驗證 import { verify } from '@solana/web3.js'
async function verifyWalletOwnership (
publicKey : string ,
signature : string ,
message : string
) {
try {
const isValid = verify (
Buffer .from (message),
Buffer .from (signature, 'base64' ),
Buffer .from (publicKey, 'base64' )
)
return isValid
} catch (error) {
return false
}
}
交易驗證 async function verifyTransaction (transaction : Transaction ) {
if (transaction.to !== expectedRecipient) {
throw new Error ('Invalid recipient' )
}
if (transaction.amount > maxAmount) {
throw new Error ('Amount exceeds limit' )
}
const balance = await getBalance (transaction.from )
if (balance < transaction.amount ) {
throw new Error ('Insufficient balance' )
}
return true
}
驗證步驟
10. 依賴安全
定期更新
npm audit
npm audit fix
npm update
npm outdated
Lock 檔案
git add package-lock.json
npm ci
驗證步驟
安全測試
自動化安全測試
test ('requires authentication' , async () => {
const response = await fetch ('/api/protected' )
expect (response.status ).toBe (401 )
})
test ('requires admin role' , async () => {
const response = await fetch ('/api/admin' , {
headers : { Authorization : `Bearer ${userToken} ` }
})
expect (response.status ).toBe (403 )
})
test ('rejects invalid input' , async () => {
const response = await fetch ('/api/users' , {
method : 'POST' ,
body : JSON .stringify ({ email : 'not-an-email' })
})
expect (response.status ).toBe (400 )
})
test ('enforces rate limits' , async () => {
const requests = Array (101 ).fill (null ).map (() =>
fetch ('/api/endpoint' )
)
const responses = await Promise .all (requests)
const tooManyRequests = responses.filter (r => r.status === 429 )
expect (tooManyRequests.length ).toBeGreaterThan (0 )
})
部署前安全檢查清單
資源
記住 :安全性不是可選的。一個漏洞可能危及整個平台。有疑慮時,選擇謹慎的做法。
原文
導航