[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AFRG1KEWT7F5E0YQPZKE38":3,"skill-same:01M6AFRG1KEWT7F5E0YQPZKE38":109},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":62,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M6AFRG1KEWT7F5E0YQPZKE38","api-security-best-practices",null,"Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities","davila7\u002Fclaude-code-templates","davila7","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6216945?v=4","01M6ADEWWFPS191NFM0Y1EX1JH","Daniel Avila","01M6ADJHGM78PHQRD3XZTFDVKK",33602,"MIT","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fapi-security-best-practices\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"security","api security","api","api security best practices","security best practices","best practices","design patterns","rate","Input Validation","api design patterns","input","rate limiting","design","patterns","protection","authentication","common","implement","vulnerabilities","authorization","secure","validation","api design","2026-11-10 10:12:30",false,"---\nname: api-security-best-practices\ndescription: \"Implement secure API design patterns including authentication, authorization, input validation, rate limiting, and protection against common API vulnerabilities\"\n---\n\n# API Security Best Practices\n\n## Overview\n\nGuide developers in building secure APIs by implementing authentication, authorization, input validation, rate limiting, and protection against common vulnerabilities. This skill covers security patterns for REST, GraphQL, and WebSocket APIs.\n\n## When to Use This Skill\n\n- Use when designing new API endpoints\n- Use when securing existing APIs\n- Use when implementing authentication and authorization\n- Use when protecting against API attacks (injection, DDoS, etc.)\n- Use when conducting API security reviews\n- Use when preparing for security audits\n- Use when implementing rate limiting and throttling\n- Use when handling sensitive data in APIs\n\n## How It Works\n\n### Step 1: Authentication & Authorization\n\nI'll help you implement secure authentication:\n- Choose authentication method (JWT, OAuth 2.0, API keys)\n- Implement token-based authentication\n- Set up role-based access control (RBAC)\n- Secure session management\n- Implement multi-factor authentication (MFA)\n\n### Step 2: Input Validation & Sanitization\n\nProtect against injection attacks:\n- Validate all input data\n- Sanitize user inputs\n- Use parameterized queries\n- Implement request schema validation\n- Prevent SQL injection, XSS, and command injection\n\n### Step 3: Rate Limiting & Throttling\n\nPrevent abuse and DDoS attacks:\n- Implement rate limiting per user\u002FIP\n- Set up API throttling\n- Configure request quotas\n- Handle rate limit errors gracefully\n- Monitor for suspicious activity\n\n### Step 4: Data Protection\n\nSecure sensitive data:\n- Encrypt data in transit (HTTPS\u002FTLS)\n- Encrypt sensitive data at rest\n- Implement proper error handling (no data leaks)\n- Sanitize error messages\n- Use secure headers\n\n### Step 5: API Security Testing\n\nVerify security implementation:\n- Test authentication and authorization\n- Perform penetration testing\n- Check for common vulnerabilities (OWASP API Top 10)\n- Validate input handling\n- Test rate limiting\n\n\n## Examples\n\n### Example 1: Implementing JWT Authentication\n\n```markdown\n## Secure JWT Authentication Implementation\n\n### Authentication Flow\n\n1. User logs in with credentials\n2. Server validates credentials\n3. Server generates JWT token\n4. Client stores token securely\n5. Client sends token with each request\n6. Server validates token\n\n### Implementation\n\n#### 1. Generate Secure JWT Tokens\n\n\\`\\`\\`javascript\n\u002F\u002F auth.js\nconst jwt = require('jsonwebtoken');\nconst bcrypt = require('bcrypt');\n\n\u002F\u002F Login endpoint\napp.post('\u002Fapi\u002Fauth\u002Flogin', async (req, res) => {\n  try {\n    const { email, password } = req.body;\n    \n    \u002F\u002F Validate input\n    if (!email || !password) {\n      return res.status(400).json({ \n        error: 'Email and password are required' \n      });\n    }\n    \n    \u002F\u002F Find user\n    const user = await db.user.findUnique({ \n      where: { email } \n    });\n    \n    if (!user) {\n      \u002F\u002F Don't reveal if user exists\n      return res.status(401).json({ \n        error: 'Invalid credentials' \n      });\n    }\n    \n    \u002F\u002F Verify password\n    const validPassword = await bcrypt.compare(\n      password, \n      user.passwordHash\n    );\n    \n    if (!validPassword) {\n      return res.status(401).json({ \n        error: 'Invalid credentials' \n      });\n    }\n    \n    \u002F\u002F Generate JWT token\n    const token = jwt.sign(\n      { \n        userId: user.id,\n        email: user.email,\n        role: user.role\n      },\n      process.env.JWT_SECRET,\n      { \n        expiresIn: '1h',\n        issuer: 'your-app',\n        audience: 'your-app-users'\n      }\n    );\n    \n    \u002F\u002F Generate refresh token\n    const refreshToken = jwt.sign(\n      { userId: user.id },\n      process.env.JWT_REFRESH_SECRET,\n      { expiresIn: '7d' }\n    );\n    \n    \u002F\u002F Store refresh token in database\n    await db.refreshToken.create({\n      data: {\n        token: refreshToken,\n        userId: user.id,\n        expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)\n      }\n    });\n    \n    res.json({\n      token,\n      refreshToken,\n      expiresIn: 3600\n    });\n    \n  } catch (error) {\n    console.error('Login error:', error);\n    res.status(500).json({ \n      error: 'An error occurred during login' \n    });\n  }\n});\n\\`\\`\\`\n\n#### 2. Verify JWT Tokens (Middleware)\n\n\\`\\`\\`javascript\n\u002F\u002F middleware\u002Fauth.js\nconst jwt = require('jsonwebtoken');\n\nfunction authenticateToken(req, res, next) {\n  \u002F\u002F Get token from header\n  const authHeader = req.headers['authorization'];\n  const token = authHeader && authHeader.split(' ')[1]; \u002F\u002F Bearer TOKEN\n  \n  if (!token) {\n    return res.status(401).json({ \n      error: 'Access token required' \n    });\n  }\n  \n  \u002F\u002F Verify token\n  jwt.verify(\n    token, \n    process.env.JWT_SECRET,\n    { \n      issuer: 'your-app',\n      audience: 'your-app-users'\n    },\n    (err, user) => {\n      if (err) {\n        if (err.name === 'TokenExpiredError') {\n          return res.status(401).json({ \n            error: 'Token expired' \n          });\n        }\n        return res.status(403).json({ \n          error: 'Invalid token' \n        });\n      }\n      \n      \u002F\u002F Attach user to request\n      req.user = user;\n      next();\n    }\n  );\n}\n\nmodule.exports = { authenticateToken };\n\\`\\`\\`\n\n#### 3. Protect Routes\n\n\\`\\`\\`javascript\nconst { authenticateToken } = require('.\u002Fmiddleware\u002Fauth');\n\n\u002F\u002F Protected route\napp.get('\u002Fapi\u002Fuser\u002Fprofile', authenticateToken, async (req, res) => {\n  try {\n    const user = await db.user.findUnique({\n      where: { id: req.user.userId },\n      select: {\n        id: true,\n        email: true,\n        name: true,\n        \u002F\u002F Don't return passwordHash\n      }\n    });\n    \n    res.json(user);\n  } catch (error) {\n    res.status(500).json({ error: 'Server error' });\n  }\n});\n\\`\\`\\`\n\n#### 4. Implement Token Refresh\n\n\\`\\`\\`javascript\napp.post('\u002Fapi\u002Fauth\u002Frefresh', async (req, res) => {\n  const { refreshToken } = req.body;\n  \n  if (!refreshToken) {\n    return res.status(401).json({ \n      error: 'Refresh token required' \n    });\n  }\n  \n  try {\n    \u002F\u002F Verify refresh token\n    const decoded = jwt.verify(\n      refreshToken, \n      process.env.JWT_REFRESH_SECRET\n    );\n    \n    \u002F\u002F Check if refresh token exists in database\n    const storedToken = await db.refreshToken.findFirst({\n      where: {\n        token: refreshToken,\n        userId: decoded.userId,\n        expiresAt: { gt: new Date() }\n      }\n    });\n    \n    if (!storedToken) {\n      return res.status(403).json({ \n        error: 'Invalid refresh token' \n      });\n    }\n    \n    \u002F\u002F Generate new access token\n    const user = await db.user.findUnique({\n      where: { id: decoded.userId }\n    });\n    \n    const newToken = jwt.sign(\n      { \n        userId: user.id,\n        email: user.email,\n        role: user.role\n      },\n      process.env.JWT_SECRET,\n      { expiresIn: '1h' }\n    );\n    \n    res.json({\n      token: newToken,\n      expiresIn: 3600\n    });\n    \n  } catch (error) {\n    res.status(403).json({ \n      error: 'Invalid refresh token' \n    });\n  }\n});\n\\`\\`\\`\n\n### Security Best Practices\n\n- ✅ Use strong JWT secrets (256-bit minimum)\n- ✅ Set short expiration times (1 hour for access tokens)\n- ✅ Implement refresh tokens for long-lived sessions\n- ✅ Store refresh tokens in database (can be revoked)\n- ✅ Use HTTPS only\n- ✅ Don't store sensitive data in JWT payload\n- ✅ Validate token issuer and audience\n- ✅ Implement token blacklisting for logout\n```\n\n\n### Example 2: Input Validation and SQL Injection Prevention\n\n```markdown\n## Preventing SQL Injection and Input Validation\n\n### The Problem\n\n**❌ Vulnerable Code:**\n\\`\\`\\`javascript\n\u002F\u002F NEVER DO THIS - SQL Injection vulnerability\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = req.params.id;\n  \n  \u002F\u002F Dangerous: User input directly in query\n  const query = \\`SELECT * FROM users WHERE id = '\\${userId}'\\`;\n  const user = await db.query(query);\n  \n  res.json(user);\n});\n\n\u002F\u002F Attack example:\n\u002F\u002F GET \u002Fapi\u002Fusers\u002F1' OR '1'='1\n\u002F\u002F Returns all users!\n\\`\\`\\`\n\n### The Solution\n\n#### 1. Use Parameterized Queries\n\n\\`\\`\\`javascript\n\u002F\u002F ✅ Safe: Parameterized query\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = req.params.id;\n  \n  \u002F\u002F Validate input first\n  if (!userId || !\u002F^\\d+$\u002F.test(userId)) {\n    return res.status(400).json({ \n      error: 'Invalid user ID' \n    });\n  }\n  \n  \u002F\u002F Use parameterized query\n  const user = await db.query(\n    'SELECT id, email, name FROM users WHERE id = $1',\n    [userId]\n  );\n  \n  if (!user) {\n    return res.status(404).json({ \n      error: 'User not found' \n    });\n  }\n  \n  res.json(user);\n});\n\\`\\`\\`\n\n#### 2. Use ORM with Proper Escaping\n\n\\`\\`\\`javascript\n\u002F\u002F ✅ Safe: Using Prisma ORM\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = parseInt(req.params.id);\n  \n  if (isNaN(userId)) {\n    return res.status(400).json({ \n      error: 'Invalid user ID' \n    });\n  }\n  \n  const user = await prisma.user.findUnique({\n    where: { id: userId },\n    select: {\n      id: true,\n      email: true,\n      name: true,\n      \u002F\u002F Don't select sensitive fields\n    }\n  });\n  \n  if (!user) {\n    return res.status(404).json({ \n      error: 'User not found' \n    });\n  }\n  \n  res.json(user);\n});\n\\`\\`\\`\n\n#### 3. Implement Request Validation with Zod\n\n\\`\\`\\`javascript\nconst { z } = require('zod');\n\n\u002F\u002F Define validation schema\nconst createUserSchema = z.object({\n  email: z.string().email('Invalid email format'),\n  password: z.string()\n    .min(8, 'Password must be at least 8 characters')\n    .regex(\u002F[A-Z]\u002F, 'Password must contain uppercase letter')\n    .regex(\u002F[a-z]\u002F, 'Password must contain lowercase letter')\n    .regex(\u002F[0-9]\u002F, 'Password must contain number'),\n  name: z.string()\n    .min(2, 'Name must be at least 2 characters')\n    .max(100, 'Name too long'),\n  age: z.number()\n    .int('Age must be an integer')\n    .min(18, 'Must be 18 or older')\n    .max(120, 'Invalid age')\n    .optional()\n});\n\n\u002F\u002F Validation middleware\nfunction validateRequest(schema) {\n  return (req, res, next) => {\n    try {\n      schema.parse(req.body);\n      next();\n    } catch (error) {\n      res.status(400).json({\n        error: 'Validation failed',\n        details: error.errors\n      });\n    }\n  };\n}\n\n\u002F\u002F Use validation\napp.post('\u002Fapi\u002Fusers', \n  validateRequest(createUserSchema),\n  async (req, res) => {\n    \u002F\u002F Input is validated at this point\n    const { email, password, name, age } = req.body;\n    \n    \u002F\u002F Hash password\n    const passwordHash = await bcrypt.hash(password, 10);\n    \n    \u002F\u002F Create user\n    const user = await prisma.user.create({\n      data: {\n        email,\n        passwordHash,\n        name,\n        age\n      }\n    });\n    \n    \u002F\u002F Don't return password hash\n    const { passwordHash: _, ...userWithoutPassword } = user;\n    res.status(201).json(userWithoutPassword);\n  }\n);\n\\`\\`\\`\n\n#### 4. Sanitize Output to Prevent XSS\n\n\\`\\`\\`javascript\nconst DOMPurify = require('isomorphic-dompurify');\n\napp.post('\u002Fapi\u002Fcomments', authenticateToken, async (req, res) => {\n  const { content } = req.body;\n  \n  \u002F\u002F Validate\n  if (!content || content.length > 1000) {\n    return res.status(400).json({ \n      error: 'Invalid comment content' \n    });\n  }\n  \n  \u002F\u002F Sanitize HTML to prevent XSS\n  const sanitizedContent = DOMPurify.sanitize(content, {\n    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],\n    ALLOWED_ATTR: ['href']\n  });\n  \n  const comment = await prisma.comment.create({\n    data: {\n      content: sanitizedContent,\n      userId: req.user.userId\n    }\n  });\n  \n  res.status(201).json(comment);\n});\n\\`\\`\\`\n\n### Validation Checklist\n\n- [ ] Validate all user inputs\n- [ ] Use parameterized queries or ORM\n- [ ] Validate data types (string, number, email, etc.)\n- [ ] Validate data ranges (min\u002Fmax length, value ranges)\n- [ ] Sanitize HTML content\n- [ ] Escape special characters\n- [ ] Validate file uploads (type, size, content)\n- [ ] Use allowlists, not blocklists\n```\n\n\n### Example 3: Rate Limiting and DDoS Protection\n\n```markdown\n## Implementing Rate Limiting\n\n### Why Rate Limiting?\n\n- Prevent brute force attacks\n- Protect against DDoS\n- Prevent API abuse\n- Ensure fair usage\n- Reduce server costs\n\n### Implementation with Express Rate Limit\n\n\\`\\`\\`javascript\nconst rateLimit = require('express-rate-limit');\nconst RedisStore = require('rate-limit-redis');\nconst Redis = require('ioredis');\n\n\u002F\u002F Create Redis client\nconst redis = new Redis({\n  host: process.env.REDIS_HOST,\n  port: process.env.REDIS_PORT\n});\n\n\u002F\u002F General API rate limit\nconst apiLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: 'rl:api:'\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 100, \u002F\u002F 100 requests per window\n  message: {\n    error: 'Too many requests, please try again later',\n    retryAfter: 900 \u002F\u002F seconds\n  },\n  standardHeaders: true, \u002F\u002F Return rate limit info in headers\n  legacyHeaders: false,\n  \u002F\u002F Custom key generator (by user ID or IP)\n  keyGenerator: (req) => {\n    return req.user?.userId || req.ip;\n  }\n});\n\n\u002F\u002F Strict rate limit for authentication endpoints\nconst authLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: 'rl:auth:'\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 5, \u002F\u002F Only 5 login attempts per 15 minutes\n  skipSuccessfulRequests: true, \u002F\u002F Don't count successful logins\n  message: {\n    error: 'Too many login attempts, please try again later',\n    retryAfter: 900\n  }\n});\n\n\u002F\u002F Apply rate limiters\napp.use('\u002Fapi\u002F', apiLimiter);\napp.use('\u002Fapi\u002Fauth\u002Flogin', authLimiter);\napp.use('\u002Fapi\u002Fauth\u002Fregister', authLimiter);\n\n\u002F\u002F Custom rate limiter for expensive operations\nconst expensiveLimiter = rateLimit({\n  windowMs: 60 * 60 * 1000, \u002F\u002F 1 hour\n  max: 10, \u002F\u002F 10 requests per hour\n  message: {\n    error: 'Rate limit exceeded for this operation'\n  }\n});\n\napp.post('\u002Fapi\u002Freports\u002Fgenerate', \n  authenticateToken,\n  expensiveLimiter,\n  async (req, res) => {\n    \u002F\u002F Expensive operation\n  }\n);\n\\`\\`\\`\n\n### Advanced: Per-User Rate Limiting\n\n\\`\\`\\`javascript\n\u002F\u002F Different limits based on user tier\nfunction createTieredRateLimiter() {\n  const limits = {\n    free: { windowMs: 60 * 60 * 1000, max: 100 },\n    pro: { windowMs: 60 * 60 * 1000, max: 1000 },\n    enterprise: { windowMs: 60 * 60 * 1000, max: 10000 }\n  };\n  \n  return async (req, res, next) => {\n    const user = req.user;\n    const tier = user?.tier || 'free';\n    const limit = limits[tier];\n    \n    const key = \\`rl:user:\\${user.userId}\\`;\n    const current = await redis.incr(key);\n    \n    if (current === 1) {\n      await redis.expire(key, limit.windowMs \u002F 1000);\n    }\n    \n    if (current > limit.max) {\n      return res.status(429).json({\n        error: 'Rate limit exceeded',\n        limit: limit.max,\n        remaining: 0,\n        reset: await redis.ttl(key)\n      });\n    }\n    \n    \u002F\u002F Set rate limit headers\n    res.set({\n      'X-RateLimit-Limit': limit.max,\n      'X-RateLimit-Remaining': limit.max - current,\n      'X-RateLimit-Reset': await redis.ttl(key)\n    });\n    \n    next();\n  };\n}\n\napp.use('\u002Fapi\u002F', authenticateToken, createTieredRateLimiter());\n\\`\\`\\`\n\n### DDoS Protection with Helmet\n\n\\`\\`\\`javascript\nconst helmet = require('helmet');\n\napp.use(helmet({\n  \u002F\u002F Content Security Policy\n  contentSecurityPolicy: {\n    directives: {\n      defaultSrc: [\"'self'\"],\n      styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n      scriptSrc: [\"'self'\"],\n      imgSrc: [\"'self'\", 'data:', 'https:']\n    }\n  },\n  \u002F\u002F Prevent clickjacking\n  frameguard: { action: 'deny' },\n  \u002F\u002F Hide X-Powered-By header\n  hidePoweredBy: true,\n  \u002F\u002F Prevent MIME type sniffing\n  noSniff: true,\n  \u002F\u002F Enable HSTS\n  hsts: {\n    maxAge: 31536000,\n    includeSubDomains: true,\n    preload: true\n  }\n}));\n\\`\\`\\`\n\n### Rate Limit Response Headers\n\n\\`\\`\\`\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 87\nX-RateLimit-Reset: 1640000000\nRetry-After: 900\n\\`\\`\\`\n```\n\n## Best Practices\n\n### ✅ Do This\n\n- **Use HTTPS Everywhere** - Never send sensitive data over HTTP\n- **Implement Authentication** - Require authentication for protected endpoints\n- **Validate All Inputs** - Never trust user input\n- **Use Parameterized Queries** - Prevent SQL injection\n- **Implement Rate Limiting** - Protect against brute force and DDoS\n- **Hash Passwords** - Use bcrypt with salt rounds >= 10\n- **Use Short-Lived Tokens** - JWT access tokens should expire quickly\n- **Implement CORS Properly** - Only allow trusted origins\n- **Log Security Events** - Monitor for suspicious activity\n- **Keep Dependencies Updated** - Regularly update packages\n- **Use Security Headers** - Implement Helmet.js\n- **Sanitize Error Messages** - Don't leak sensitive information\n\n### ❌ Don't Do This\n\n- **Don't Store Passwords in Plain Text** - Always hash passwords\n- **Don't Use Weak Secrets** - Use strong, random JWT secrets\n- **Don't Trust User Input** - Always validate and sanitize\n- **Don't Expose Stack Traces** - Hide error details in production\n- **Don't Use String Concatenation for SQL** - Use parameterized queries\n- **Don't Store Sensitive Data in JWT** - JWTs are not encrypted\n- **Don't Ignore Security Updates** - Update dependencies regularly\n- **Don't Use Default Credentials** - Change all default passwords\n- **Don't Disable CORS Completely** - Configure it properly instead\n- **Don't Log Sensitive Data** - Sanitize logs\n\n## Common Pitfalls\n\n### Problem: JWT Secret Exposed in Code\n**Symptoms:** JWT secret hardcoded or committed to Git\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad\nconst JWT_SECRET = 'my-secret-key';\n\n\u002F\u002F ✅ Good\nconst JWT_SECRET = process.env.JWT_SECRET;\nif (!JWT_SECRET) {\n  throw new Error('JWT_SECRET environment variable is required');\n}\n\n\u002F\u002F Generate strong secret\n\u002F\u002F node -e \"console.log(require('crypto').randomBytes(64).toString('hex'))\"\n\\`\\`\\`\n\n### Problem: Weak Password Requirements\n**Symptoms:** Users can set weak passwords like \"password123\"\n**Solution:**\n\\`\\`\\`javascript\nconst passwordSchema = z.string()\n  .min(12, 'Password must be at least 12 characters')\n  .regex(\u002F[A-Z]\u002F, 'Must contain uppercase letter')\n  .regex(\u002F[a-z]\u002F, 'Must contain lowercase letter')\n  .regex(\u002F[0-9]\u002F, 'Must contain number')\n  .regex(\u002F[^A-Za-z0-9]\u002F, 'Must contain special character');\n\n\u002F\u002F Or use a password strength library\nconst zxcvbn = require('zxcvbn');\nconst result = zxcvbn(password);\nif (result.score \u003C 3) {\n  return res.status(400).json({\n    error: 'Password too weak',\n    suggestions: result.feedback.suggestions\n  });\n}\n\\`\\`\\`\n\n### Problem: Missing Authorization Checks\n**Symptoms:** Users can access resources they shouldn't\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad: Only checks authentication\napp.delete('\u002Fapi\u002Fposts\u002F:id', authenticateToken, async (req, res) => {\n  await prisma.post.delete({ where: { id: req.params.id } });\n  res.json({ success: true });\n});\n\n\u002F\u002F ✅ Good: Checks both authentication and authorization\napp.delete('\u002Fapi\u002Fposts\u002F:id', authenticateToken, async (req, res) => {\n  const post = await prisma.post.findUnique({\n    where: { id: req.params.id }\n  });\n  \n  if (!post) {\n    return res.status(404).json({ error: 'Post not found' });\n  }\n  \n  \u002F\u002F Check if user owns the post or is admin\n  if (post.userId !== req.user.userId && req.user.role !== 'admin') {\n    return res.status(403).json({ \n      error: 'Not authorized to delete this post' \n    });\n  }\n  \n  await prisma.post.delete({ where: { id: req.params.id } });\n  res.json({ success: true });\n});\n\\`\\`\\`\n\n### Problem: Verbose Error Messages\n**Symptoms:** Error messages reveal system details\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad: Exposes database details\napp.post('\u002Fapi\u002Fusers', async (req, res) => {\n  try {\n    const user = await prisma.user.create({ data: req.body });\n    res.json(user);\n  } catch (error) {\n    res.status(500).json({ error: error.message });\n    \u002F\u002F Error: \"Unique constraint failed on the fields: (`email`)\"\n  }\n});\n\n\u002F\u002F ✅ Good: Generic error message\napp.post('\u002Fapi\u002Fusers', async (req, res) => {\n  try {\n    const user = await prisma.user.create({ data: req.body });\n    res.json(user);\n  } catch (error) {\n    console.error('User creation error:', error); \u002F\u002F Log full error\n    \n    if (error.code === 'P2002') {\n      return res.status(400).json({ \n        error: 'Email already exists' \n      });\n    }\n    \n    res.status(500).json({ \n      error: 'An error occurred while creating user' \n    });\n  }\n});\n\\`\\`\\`\n\n## Security Checklist\n\n### Authentication & Authorization\n- [ ] Implement strong authentication (JWT, OAuth 2.0)\n- [ ] Use HTTPS for all endpoints\n- [ ] Hash passwords with bcrypt (salt rounds >= 10)\n- [ ] Implement token expiration\n- [ ] Add refresh token mechanism\n- [ ] Verify user authorization for each request\n- [ ] Implement role-based access control (RBAC)\n\n### Input Validation\n- [ ] Validate all user inputs\n- [ ] Use parameterized queries or ORM\n- [ ] Sanitize HTML content\n- [ ] Validate file uploads\n- [ ] Implement request schema validation\n- [ ] Use allowlists, not blocklists\n\n### Rate Limiting & DDoS Protection\n- [ ] Implement rate limiting per user\u002FIP\n- [ ] Add stricter limits for auth endpoints\n- [ ] Use Redis for distributed rate limiting\n- [ ] Return proper rate limit headers\n- [ ] Implement request throttling\n\n### Data Protection\n- [ ] Use HTTPS\u002FTLS for all traffic\n- [ ] Encrypt sensitive data at rest\n- [ ] Don't store sensitive data in JWT\n- [ ] Sanitize error messages\n- [ ] Implement proper CORS configuration\n- [ ] Use security headers (Helmet.js)\n\n### Monitoring & Logging\n- [ ] Log security events\n- [ ] Monitor for suspicious activity\n- [ ] Set up alerts for failed auth attempts\n- [ ] Track API usage patterns\n- [ ] Don't log sensitive data\n\n## OWASP API Security Top 10\n\n1. **Broken Object Level Authorization** - Always verify user can access resource\n2. **Broken Authentication** - Implement strong authentication mechanisms\n3. **Broken Object Property Level Authorization** - Validate which properties user can access\n4. **Unrestricted Resource Consumption** - Implement rate limiting and quotas\n5. **Broken Function Level Authorization** - Verify user role for each function\n6. **Unrestricted Access to Sensitive Business Flows** - Protect critical workflows\n7. **Server Side Request Forgery (SSRF)** - Validate and sanitize URLs\n8. **Security Misconfiguration** - Use security best practices and headers\n9. **Improper Inventory Management** - Document and secure all API endpoints\n10. **Unsafe Consumption of APIs** - Validate data from third-party APIs\n\n## Related Skills\n\n- `@ethical-hacking-methodology` - Security testing perspective\n- `@sql-injection-testing` - Testing for SQL injection\n- `@xss-html-injection` - Testing for XSS vulnerabilities\n- `@broken-authentication` - Authentication vulnerabilities\n- `@backend-dev-guidelines` - Backend development standards\n- `@systematic-debugging` - Debug security issues\n\n## Additional Resources\n\n- [OWASP API Security Top 10](https:\u002F\u002Fowasp.org\u002Fwww-project-api-security\u002F)\n- [JWT Best Practices](https:\u002F\u002Ftools.ietf.org\u002Fhtml\u002Frfc8725)\n- [Express Security Best Practices](https:\u002F\u002Fexpressjs.com\u002Fen\u002Fadvanced\u002Fbest-practice-security.html)\n- [Node.js Security Checklist](https:\u002F\u002Fblog.risingstack.com\u002Fnode-js-security-checklist\u002F)\n- [API Security Checklist](https:\u002F\u002Fgithub.com\u002Fshieldfy\u002FAPI-Security-Checklist)\n\n---\n\n**Pro Tip:** Security is not a one-time task - regularly audit your APIs, keep dependencies updated, and stay informed about new vulnerabilities!\n","# API Security Best Practices\n\n## Overview\n\nGuide developers in building secure APIs by implementing authentication, authorization, input validation, rate limiting, and protection against common vulnerabilities. This skill covers security patterns for REST, GraphQL, and WebSocket APIs.\n\n## When to Use This Skill\n\n- Use when designing new API endpoints\n- Use when securing existing APIs\n- Use when implementing authentication and authorization\n- Use when protecting against API attacks (injection, DDoS, etc.)\n- Use when conducting API security reviews\n- Use when preparing for security audits\n- Use when implementing rate limiting and throttling\n- Use when handling sensitive data in APIs\n\n## How It Works\n\n### Step 1: Authentication & Authorization\n\nI'll help you implement secure authentication:\n- Choose authentication method (JWT, OAuth 2.0, API keys)\n- Implement token-based authentication\n- Set up role-based access control (RBAC)\n- Secure session management\n- Implement multi-factor authentication (MFA)\n\n### Step 2: Input Validation & Sanitization\n\nProtect against injection attacks:\n- Validate all input data\n- Sanitize user inputs\n- Use parameterized queries\n- Implement request schema validation\n- Prevent SQL injection, XSS, and command injection\n\n### Step 3: Rate Limiting & Throttling\n\nPrevent abuse and DDoS attacks:\n- Implement rate limiting per user\u002FIP\n- Set up API throttling\n- Configure request quotas\n- Handle rate limit errors gracefully\n- Monitor for suspicious activity\n\n### Step 4: Data Protection\n\nSecure sensitive data:\n- Encrypt data in transit (HTTPS\u002FTLS)\n- Encrypt sensitive data at rest\n- Implement proper error handling (no data leaks)\n- Sanitize error messages\n- Use secure headers\n\n### Step 5: API Security Testing\n\nVerify security implementation:\n- Test authentication and authorization\n- Perform penetration testing\n- Check for common vulnerabilities (OWASP API Top 10)\n- Validate input handling\n- Test rate limiting\n\n\n## Examples\n\n### Example 1: Implementing JWT Authentication\n\n```markdown\n## Secure JWT Authentication Implementation\n\n### Authentication Flow\n\n1. User logs in with credentials\n2. Server validates credentials\n3. Server generates JWT token\n4. Client stores token securely\n5. Client sends token with each request\n6. Server validates token\n\n### Implementation\n\n#### 1. Generate Secure JWT Tokens\n\n\\`\\`\\`javascript\n\u002F\u002F auth.js\nconst jwt = require('jsonwebtoken');\nconst bcrypt = require('bcrypt');\n\n\u002F\u002F Login endpoint\napp.post('\u002Fapi\u002Fauth\u002Flogin', async (req, res) => {\n  try {\n    const { email, password } = req.body;\n    \n    \u002F\u002F Validate input\n    if (!email || !password) {\n      return res.status(400).json({ \n        error: 'Email and password are required' \n      });\n    }\n    \n    \u002F\u002F Find user\n    const user = await db.user.findUnique({ \n      where: { email } \n    });\n    \n    if (!user) {\n      \u002F\u002F Don't reveal if user exists\n      return res.status(401).json({ \n        error: 'Invalid credentials' \n      });\n    }\n    \n    \u002F\u002F Verify password\n    const validPassword = await bcrypt.compare(\n      password, \n      user.passwordHash\n    );\n    \n    if (!validPassword) {\n      return res.status(401).json({ \n        error: 'Invalid credentials' \n      });\n    }\n    \n    \u002F\u002F Generate JWT token\n    const token = jwt.sign(\n      { \n        userId: user.id,\n        email: user.email,\n        role: user.role\n      },\n      process.env.JWT_SECRET,\n      { \n        expiresIn: '1h',\n        issuer: 'your-app',\n        audience: 'your-app-users'\n      }\n    );\n    \n    \u002F\u002F Generate refresh token\n    const refreshToken = jwt.sign(\n      { userId: user.id },\n      process.env.JWT_REFRESH_SECRET,\n      { expiresIn: '7d' }\n    );\n    \n    \u002F\u002F Store refresh token in database\n    await db.refreshToken.create({\n      data: {\n        token: refreshToken,\n        userId: user.id,\n        expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)\n      }\n    });\n    \n    res.json({\n      token,\n      refreshToken,\n      expiresIn: 3600\n    });\n    \n  } catch (error) {\n    console.error('Login error:', error);\n    res.status(500).json({ \n      error: 'An error occurred during login' \n    });\n  }\n});\n\\`\\`\\`\n\n#### 2. Verify JWT Tokens (Middleware)\n\n\\`\\`\\`javascript\n\u002F\u002F middleware\u002Fauth.js\nconst jwt = require('jsonwebtoken');\n\nfunction authenticateToken(req, res, next) {\n  \u002F\u002F Get token from header\n  const authHeader = req.headers['authorization'];\n  const token = authHeader && authHeader.split(' ')[1]; \u002F\u002F Bearer TOKEN\n  \n  if (!token) {\n    return res.status(401).json({ \n      error: 'Access token required' \n    });\n  }\n  \n  \u002F\u002F Verify token\n  jwt.verify(\n    token, \n    process.env.JWT_SECRET,\n    { \n      issuer: 'your-app',\n      audience: 'your-app-users'\n    },\n    (err, user) => {\n      if (err) {\n        if (err.name === 'TokenExpiredError') {\n          return res.status(401).json({ \n            error: 'Token expired' \n          });\n        }\n        return res.status(403).json({ \n          error: 'Invalid token' \n        });\n      }\n      \n      \u002F\u002F Attach user to request\n      req.user = user;\n      next();\n    }\n  );\n}\n\nmodule.exports = { authenticateToken };\n\\`\\`\\`\n\n#### 3. Protect Routes\n\n\\`\\`\\`javascript\nconst { authenticateToken } = require('.\u002Fmiddleware\u002Fauth');\n\n\u002F\u002F Protected route\napp.get('\u002Fapi\u002Fuser\u002Fprofile', authenticateToken, async (req, res) => {\n  try {\n    const user = await db.user.findUnique({\n      where: { id: req.user.userId },\n      select: {\n        id: true,\n        email: true,\n        name: true,\n        \u002F\u002F Don't return passwordHash\n      }\n    });\n    \n    res.json(user);\n  } catch (error) {\n    res.status(500).json({ error: 'Server error' });\n  }\n});\n\\`\\`\\`\n\n#### 4. Implement Token Refresh\n\n\\`\\`\\`javascript\napp.post('\u002Fapi\u002Fauth\u002Frefresh', async (req, res) => {\n  const { refreshToken } = req.body;\n  \n  if (!refreshToken) {\n    return res.status(401).json({ \n      error: 'Refresh token required' \n    });\n  }\n  \n  try {\n    \u002F\u002F Verify refresh token\n    const decoded = jwt.verify(\n      refreshToken, \n      process.env.JWT_REFRESH_SECRET\n    );\n    \n    \u002F\u002F Check if refresh token exists in database\n    const storedToken = await db.refreshToken.findFirst({\n      where: {\n        token: refreshToken,\n        userId: decoded.userId,\n        expiresAt: { gt: new Date() }\n      }\n    });\n    \n    if (!storedToken) {\n      return res.status(403).json({ \n        error: 'Invalid refresh token' \n      });\n    }\n    \n    \u002F\u002F Generate new access token\n    const user = await db.user.findUnique({\n      where: { id: decoded.userId }\n    });\n    \n    const newToken = jwt.sign(\n      { \n        userId: user.id,\n        email: user.email,\n        role: user.role\n      },\n      process.env.JWT_SECRET,\n      { expiresIn: '1h' }\n    );\n    \n    res.json({\n      token: newToken,\n      expiresIn: 3600\n    });\n    \n  } catch (error) {\n    res.status(403).json({ \n      error: 'Invalid refresh token' \n    });\n  }\n});\n\\`\\`\\`\n\n### Security Best Practices\n\n- ✅ Use strong JWT secrets (256-bit minimum)\n- ✅ Set short expiration times (1 hour for access tokens)\n- ✅ Implement refresh tokens for long-lived sessions\n- ✅ Store refresh tokens in database (can be revoked)\n- ✅ Use HTTPS only\n- ✅ Don't store sensitive data in JWT payload\n- ✅ Validate token issuer and audience\n- ✅ Implement token blacklisting for logout\n```\n\n\n### Example 2: Input Validation and SQL Injection Prevention\n\n```markdown\n## Preventing SQL Injection and Input Validation\n\n### The Problem\n\n**❌ Vulnerable Code:**\n\\`\\`\\`javascript\n\u002F\u002F NEVER DO THIS - SQL Injection vulnerability\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = req.params.id;\n  \n  \u002F\u002F Dangerous: User input directly in query\n  const query = \\`SELECT * FROM users WHERE id = '\\${userId}'\\`;\n  const user = await db.query(query);\n  \n  res.json(user);\n});\n\n\u002F\u002F Attack example:\n\u002F\u002F GET \u002Fapi\u002Fusers\u002F1' OR '1'='1\n\u002F\u002F Returns all users!\n\\`\\`\\`\n\n### The Solution\n\n#### 1. Use Parameterized Queries\n\n\\`\\`\\`javascript\n\u002F\u002F ✅ Safe: Parameterized query\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = req.params.id;\n  \n  \u002F\u002F Validate input first\n  if (!userId || !\u002F^\\d+$\u002F.test(userId)) {\n    return res.status(400).json({ \n      error: 'Invalid user ID' \n    });\n  }\n  \n  \u002F\u002F Use parameterized query\n  const user = await db.query(\n    'SELECT id, email, name FROM users WHERE id = $1',\n    [userId]\n  );\n  \n  if (!user) {\n    return res.status(404).json({ \n      error: 'User not found' \n    });\n  }\n  \n  res.json(user);\n});\n\\`\\`\\`\n\n#### 2. Use ORM with Proper Escaping\n\n\\`\\`\\`javascript\n\u002F\u002F ✅ Safe: Using Prisma ORM\napp.get('\u002Fapi\u002Fusers\u002F:id', async (req, res) => {\n  const userId = parseInt(req.params.id);\n  \n  if (isNaN(userId)) {\n    return res.status(400).json({ \n      error: 'Invalid user ID' \n    });\n  }\n  \n  const user = await prisma.user.findUnique({\n    where: { id: userId },\n    select: {\n      id: true,\n      email: true,\n      name: true,\n      \u002F\u002F Don't select sensitive fields\n    }\n  });\n  \n  if (!user) {\n    return res.status(404).json({ \n      error: 'User not found' \n    });\n  }\n  \n  res.json(user);\n});\n\\`\\`\\`\n\n#### 3. Implement Request Validation with Zod\n\n\\`\\`\\`javascript\nconst { z } = require('zod');\n\n\u002F\u002F Define validation schema\nconst createUserSchema = z.object({\n  email: z.string().email('Invalid email format'),\n  password: z.string()\n    .min(8, 'Password must be at least 8 characters')\n    .regex(\u002F[A-Z]\u002F, 'Password must contain uppercase letter')\n    .regex(\u002F[a-z]\u002F, 'Password must contain lowercase letter')\n    .regex(\u002F[0-9]\u002F, 'Password must contain number'),\n  name: z.string()\n    .min(2, 'Name must be at least 2 characters')\n    .max(100, 'Name too long'),\n  age: z.number()\n    .int('Age must be an integer')\n    .min(18, 'Must be 18 or older')\n    .max(120, 'Invalid age')\n    .optional()\n});\n\n\u002F\u002F Validation middleware\nfunction validateRequest(schema) {\n  return (req, res, next) => {\n    try {\n      schema.parse(req.body);\n      next();\n    } catch (error) {\n      res.status(400).json({\n        error: 'Validation failed',\n        details: error.errors\n      });\n    }\n  };\n}\n\n\u002F\u002F Use validation\napp.post('\u002Fapi\u002Fusers', \n  validateRequest(createUserSchema),\n  async (req, res) => {\n    \u002F\u002F Input is validated at this point\n    const { email, password, name, age } = req.body;\n    \n    \u002F\u002F Hash password\n    const passwordHash = await bcrypt.hash(password, 10);\n    \n    \u002F\u002F Create user\n    const user = await prisma.user.create({\n      data: {\n        email,\n        passwordHash,\n        name,\n        age\n      }\n    });\n    \n    \u002F\u002F Don't return password hash\n    const { passwordHash: _, ...userWithoutPassword } = user;\n    res.status(201).json(userWithoutPassword);\n  }\n);\n\\`\\`\\`\n\n#### 4. Sanitize Output to Prevent XSS\n\n\\`\\`\\`javascript\nconst DOMPurify = require('isomorphic-dompurify');\n\napp.post('\u002Fapi\u002Fcomments', authenticateToken, async (req, res) => {\n  const { content } = req.body;\n  \n  \u002F\u002F Validate\n  if (!content || content.length > 1000) {\n    return res.status(400).json({ \n      error: 'Invalid comment content' \n    });\n  }\n  \n  \u002F\u002F Sanitize HTML to prevent XSS\n  const sanitizedContent = DOMPurify.sanitize(content, {\n    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],\n    ALLOWED_ATTR: ['href']\n  });\n  \n  const comment = await prisma.comment.create({\n    data: {\n      content: sanitizedContent,\n      userId: req.user.userId\n    }\n  });\n  \n  res.status(201).json(comment);\n});\n\\`\\`\\`\n\n### Validation Checklist\n\n- [ ] Validate all user inputs\n- [ ] Use parameterized queries or ORM\n- [ ] Validate data types (string, number, email, etc.)\n- [ ] Validate data ranges (min\u002Fmax length, value ranges)\n- [ ] Sanitize HTML content\n- [ ] Escape special characters\n- [ ] Validate file uploads (type, size, content)\n- [ ] Use allowlists, not blocklists\n```\n\n\n### Example 3: Rate Limiting and DDoS Protection\n\n```markdown\n## Implementing Rate Limiting\n\n### Why Rate Limiting?\n\n- Prevent brute force attacks\n- Protect against DDoS\n- Prevent API abuse\n- Ensure fair usage\n- Reduce server costs\n\n### Implementation with Express Rate Limit\n\n\\`\\`\\`javascript\nconst rateLimit = require('express-rate-limit');\nconst RedisStore = require('rate-limit-redis');\nconst Redis = require('ioredis');\n\n\u002F\u002F Create Redis client\nconst redis = new Redis({\n  host: process.env.REDIS_HOST,\n  port: process.env.REDIS_PORT\n});\n\n\u002F\u002F General API rate limit\nconst apiLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: 'rl:api:'\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 100, \u002F\u002F 100 requests per window\n  message: {\n    error: 'Too many requests, please try again later',\n    retryAfter: 900 \u002F\u002F seconds\n  },\n  standardHeaders: true, \u002F\u002F Return rate limit info in headers\n  legacyHeaders: false,\n  \u002F\u002F Custom key generator (by user ID or IP)\n  keyGenerator: (req) => {\n    return req.user?.userId || req.ip;\n  }\n});\n\n\u002F\u002F Strict rate limit for authentication endpoints\nconst authLimiter = rateLimit({\n  store: new RedisStore({\n    client: redis,\n    prefix: 'rl:auth:'\n  }),\n  windowMs: 15 * 60 * 1000, \u002F\u002F 15 minutes\n  max: 5, \u002F\u002F Only 5 login attempts per 15 minutes\n  skipSuccessfulRequests: true, \u002F\u002F Don't count successful logins\n  message: {\n    error: 'Too many login attempts, please try again later',\n    retryAfter: 900\n  }\n});\n\n\u002F\u002F Apply rate limiters\napp.use('\u002Fapi\u002F', apiLimiter);\napp.use('\u002Fapi\u002Fauth\u002Flogin', authLimiter);\napp.use('\u002Fapi\u002Fauth\u002Fregister', authLimiter);\n\n\u002F\u002F Custom rate limiter for expensive operations\nconst expensiveLimiter = rateLimit({\n  windowMs: 60 * 60 * 1000, \u002F\u002F 1 hour\n  max: 10, \u002F\u002F 10 requests per hour\n  message: {\n    error: 'Rate limit exceeded for this operation'\n  }\n});\n\napp.post('\u002Fapi\u002Freports\u002Fgenerate', \n  authenticateToken,\n  expensiveLimiter,\n  async (req, res) => {\n    \u002F\u002F Expensive operation\n  }\n);\n\\`\\`\\`\n\n### Advanced: Per-User Rate Limiting\n\n\\`\\`\\`javascript\n\u002F\u002F Different limits based on user tier\nfunction createTieredRateLimiter() {\n  const limits = {\n    free: { windowMs: 60 * 60 * 1000, max: 100 },\n    pro: { windowMs: 60 * 60 * 1000, max: 1000 },\n    enterprise: { windowMs: 60 * 60 * 1000, max: 10000 }\n  };\n  \n  return async (req, res, next) => {\n    const user = req.user;\n    const tier = user?.tier || 'free';\n    const limit = limits[tier];\n    \n    const key = \\`rl:user:\\${user.userId}\\`;\n    const current = await redis.incr(key);\n    \n    if (current === 1) {\n      await redis.expire(key, limit.windowMs \u002F 1000);\n    }\n    \n    if (current > limit.max) {\n      return res.status(429).json({\n        error: 'Rate limit exceeded',\n        limit: limit.max,\n        remaining: 0,\n        reset: await redis.ttl(key)\n      });\n    }\n    \n    \u002F\u002F Set rate limit headers\n    res.set({\n      'X-RateLimit-Limit': limit.max,\n      'X-RateLimit-Remaining': limit.max - current,\n      'X-RateLimit-Reset': await redis.ttl(key)\n    });\n    \n    next();\n  };\n}\n\napp.use('\u002Fapi\u002F', authenticateToken, createTieredRateLimiter());\n\\`\\`\\`\n\n### DDoS Protection with Helmet\n\n\\`\\`\\`javascript\nconst helmet = require('helmet');\n\napp.use(helmet({\n  \u002F\u002F Content Security Policy\n  contentSecurityPolicy: {\n    directives: {\n      defaultSrc: [\"'self'\"],\n      styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n      scriptSrc: [\"'self'\"],\n      imgSrc: [\"'self'\", 'data:', 'https:']\n    }\n  },\n  \u002F\u002F Prevent clickjacking\n  frameguard: { action: 'deny' },\n  \u002F\u002F Hide X-Powered-By header\n  hidePoweredBy: true,\n  \u002F\u002F Prevent MIME type sniffing\n  noSniff: true,\n  \u002F\u002F Enable HSTS\n  hsts: {\n    maxAge: 31536000,\n    includeSubDomains: true,\n    preload: true\n  }\n}));\n\\`\\`\\`\n\n### Rate Limit Response Headers\n\n\\`\\`\\`\nX-RateLimit-Limit: 100\nX-RateLimit-Remaining: 87\nX-RateLimit-Reset: 1640000000\nRetry-After: 900\n\\`\\`\\`\n```\n\n## Best Practices\n\n### ✅ Do This\n\n- **Use HTTPS Everywhere** - Never send sensitive data over HTTP\n- **Implement Authentication** - Require authentication for protected endpoints\n- **Validate All Inputs** - Never trust user input\n- **Use Parameterized Queries** - Prevent SQL injection\n- **Implement Rate Limiting** - Protect against brute force and DDoS\n- **Hash Passwords** - Use bcrypt with salt rounds >= 10\n- **Use Short-Lived Tokens** - JWT access tokens should expire quickly\n- **Implement CORS Properly** - Only allow trusted origins\n- **Log Security Events** - Monitor for suspicious activity\n- **Keep Dependencies Updated** - Regularly update packages\n- **Use Security Headers** - Implement Helmet.js\n- **Sanitize Error Messages** - Don't leak sensitive information\n\n### ❌ Don't Do This\n\n- **Don't Store Passwords in Plain Text** - Always hash passwords\n- **Don't Use Weak Secrets** - Use strong, random JWT secrets\n- **Don't Trust User Input** - Always validate and sanitize\n- **Don't Expose Stack Traces** - Hide error details in production\n- **Don't Use String Concatenation for SQL** - Use parameterized queries\n- **Don't Store Sensitive Data in JWT** - JWTs are not encrypted\n- **Don't Ignore Security Updates** - Update dependencies regularly\n- **Don't Use Default Credentials** - Change all default passwords\n- **Don't Disable CORS Completely** - Configure it properly instead\n- **Don't Log Sensitive Data** - Sanitize logs\n\n## Common Pitfalls\n\n### Problem: JWT Secret Exposed in Code\n**Symptoms:** JWT secret hardcoded or committed to Git\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad\nconst JWT_SECRET = 'my-secret-key';\n\n\u002F\u002F ✅ Good\nconst JWT_SECRET = process.env.JWT_SECRET;\nif (!JWT_SECRET) {\n  throw new Error('JWT_SECRET environment variable is required');\n}\n\n\u002F\u002F Generate strong secret\n\u002F\u002F node -e \"console.log(require('crypto').randomBytes(64).toString('hex'))\"\n\\`\\`\\`\n\n### Problem: Weak Password Requirements\n**Symptoms:** Users can set weak passwords like \"password123\"\n**Solution:**\n\\`\\`\\`javascript\nconst passwordSchema = z.string()\n  .min(12, 'Password must be at least 12 characters')\n  .regex(\u002F[A-Z]\u002F, 'Must contain uppercase letter')\n  .regex(\u002F[a-z]\u002F, 'Must contain lowercase letter')\n  .regex(\u002F[0-9]\u002F, 'Must contain number')\n  .regex(\u002F[^A-Za-z0-9]\u002F, 'Must contain special character');\n\n\u002F\u002F Or use a password strength library\nconst zxcvbn = require('zxcvbn');\nconst result = zxcvbn(password);\nif (result.score \u003C 3) {\n  return res.status(400).json({\n    error: 'Password too weak',\n    suggestions: result.feedback.suggestions\n  });\n}\n\\`\\`\\`\n\n### Problem: Missing Authorization Checks\n**Symptoms:** Users can access resources they shouldn't\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad: Only checks authentication\napp.delete('\u002Fapi\u002Fposts\u002F:id', authenticateToken, async (req, res) => {\n  await prisma.post.delete({ where: { id: req.params.id } });\n  res.json({ success: true });\n});\n\n\u002F\u002F ✅ Good: Checks both authentication and authorization\napp.delete('\u002Fapi\u002Fposts\u002F:id', authenticateToken, async (req, res) => {\n  const post = await prisma.post.findUnique({\n    where: { id: req.params.id }\n  });\n  \n  if (!post) {\n    return res.status(404).json({ error: 'Post not found' });\n  }\n  \n  \u002F\u002F Check if user owns the post or is admin\n  if (post.userId !== req.user.userId && req.user.role !== 'admin') {\n    return res.status(403).json({ \n      error: 'Not authorized to delete this post' \n    });\n  }\n  \n  await prisma.post.delete({ where: { id: req.params.id } });\n  res.json({ success: true });\n});\n\\`\\`\\`\n\n### Problem: Verbose Error Messages\n**Symptoms:** Error messages reveal system details\n**Solution:**\n\\`\\`\\`javascript\n\u002F\u002F ❌ Bad: Exposes database details\napp.post('\u002Fapi\u002Fusers', async (req, res) => {\n  try {\n    const user = await prisma.user.create({ data: req.body });\n    res.json(user);\n  } catch (error) {\n    res.status(500).json({ error: error.message });\n    \u002F\u002F Error: \"Unique constraint failed on the fields: (`email`)\"\n  }\n});\n\n\u002F\u002F ✅ Good: Generic error message\napp.post('\u002Fapi\u002Fusers', async (req, res) => {\n  try {\n    const user = await prisma.user.create({ data: req.body });\n    res.json(user);\n  } catch (error) {\n    console.error('User creation error:', error); \u002F\u002F Log full error\n    \n    if (error.code === 'P2002') {\n      return res.status(400).json({ \n        error: 'Email already exists' \n      });\n    }\n    \n    res.status(500).json({ \n      error: 'An error occurred while creating user' \n    });\n  }\n});\n\\`\\`\\`\n\n## Security Checklist\n\n### Authentication & Authorization\n- [ ] Implement strong authentication (JWT, OAuth 2.0)\n- [ ] Use HTTPS for all endpoints\n- [ ] Hash passwords with bcrypt (salt rounds >= 10)\n- [ ] Implement token expiration\n- [ ] Add refresh token mechanism\n- [ ] Verify user authorization for each request\n- [ ] Implement role-based access control (RBAC)\n\n### Input Validation\n- [ ] Validate all user inputs\n- [ ] Use parameterized queries or ORM\n- [ ] Sanitize HTML content\n- [ ] Validate file uploads\n- [ ] Implement request schema validation\n- [ ] Use allowlists, not blocklists\n\n### Rate Limiting & DDoS Protection\n- [ ] Implement rate limiting per user\u002FIP\n- [ ] Add stricter limits for auth endpoints\n- [ ] Use Redis for distributed rate limiting\n- [ ] Return proper rate limit headers\n- [ ] Implement request throttling\n\n### Data Protection\n- [ ] Use HTTPS\u002FTLS for all traffic\n- [ ] Encrypt sensitive data at rest\n- [ ] Don't store sensitive data in JWT\n- [ ] Sanitize error messages\n- [ ] Implement proper CORS configuration\n- [ ] Use security headers (Helmet.js)\n\n### Monitoring & Logging\n- [ ] Log security events\n- [ ] Monitor for suspicious activity\n- [ ] Set up alerts for failed auth attempts\n- [ ] Track API usage patterns\n- [ ] Don't log sensitive data\n\n## OWASP API Security Top 10\n\n1. **Broken Object Level Authorization** - Always verify user can access resource\n2. **Broken Authentication** - Implement strong authentication mechanisms\n3. **Broken Object Property Level Authorization** - Validate which properties user can access\n4. **Unrestricted Resource Consumption** - Implement rate limiting and quotas\n5. **Broken Function Level Authorization** - Verify user role for each function\n6. **Unrestricted Access to Sensitive Business Flows** - Protect critical workflows\n7. **Server Side Request Forgery (SSRF)** - Validate and sanitize URLs\n8. **Security Misconfiguration** - Use security best practices and headers\n9. **Improper Inventory Management** - Document and secure all API endpoints\n10. **Unsafe Consumption of APIs** - Validate data from third-party APIs\n\n## Related Skills\n\n- `@ethical-hacking-methodology` - Security testing perspective\n- `@sql-injection-testing` - Testing for SQL injection\n- `@xss-html-injection` - Testing for XSS vulnerabilities\n- `@broken-authentication` - Authentication vulnerabilities\n- `@backend-dev-guidelines` - Backend development standards\n- `@systematic-debugging` - Debug security issues\n\n## Additional Resources\n\n- [OWASP API Security Top 10](https:\u002F\u002Fowasp.org\u002Fwww-project-api-security\u002F)\n- [JWT Best Practices](https:\u002F\u002Ftools.ietf.org\u002Fhtml\u002Frfc8725)\n- [Express Security Best Practices](https:\u002F\u002Fexpressjs.com\u002Fen\u002Fadvanced\u002Fbest-practice-security.html)\n- [Node.js Security Checklist](https:\u002F\u002Fblog.risingstack.com\u002Fnode-js-security-checklist\u002F)\n- [API Security Checklist](https:\u002F\u002Fgithub.com\u002Fshieldfy\u002FAPI-Security-Checklist)\n\n---\n\n**Pro Tip:** Security is not a one-time task - regularly audit your APIs, keep dependencies updated, and stay informed about new vulnerabilities!\n",{"name":5,"description":7},"main","2b749c82b5d11fac39d9a6e021ce3f5b8a541bd1","cli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fapi-security-best-practices",3963,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates","https:\u002F\u002Faitmpl.com","https:\u002F\u002Fgithub.com\u002Fdavila7","https:\u002F\u002Fdanielavila.me","Building AI dev tools with LLMs","2026-11-15 01:32:48",{"source":8,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add davila7\u002Fclaude-code-templates --skill api-security-best-practices",{"tool":73,"command":74},"bunx","bunx skills add davila7\u002Fclaude-code-templates --skill api-security-best-practices",{"tool":76,"command":77},"pnpm","pnpm dlx skills add davila7\u002Fclaude-code-templates --skill api-security-best-practices","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fapi-security-best-practices\u002FSKILL.md",true,[81,87,91,95,99,105],{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"exceptions.md","REFERENCE","参考文档",10327,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Fexceptions.md",{"path":88,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":89,"sourceHtmlUrl":90},"review-records.md",13286,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Freview-records.md",{"path":92,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":93,"sourceHtmlUrl":94},"review-recovery.md",4255,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Freview-recovery.md",{"path":96,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":97,"sourceHtmlUrl":98},"review-routing.md",23236,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Freview-routing.md",{"path":100,"resourceType":101,"resourceTypeDesc":102,"sizeBytes":103,"sourceHtmlUrl":104},"scripts\u002Fpr-base-changed-paths.sh","SCRIPT","脚本",2473,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Fscripts\u002Fpr-base-changed-paths.sh",{"path":106,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":107,"sourceHtmlUrl":108},"six-stage.md",14625,"https:\u002F\u002Fgithub.com\u002Fjleechanorg\u002Fjleechan-skills\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-lifecycle\u002Fsix-stage.md",[110,140,167,196,231,255],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":119,"publishedAt":52},"01M70NHBTQ8BV0A2SCAZXEPHCX","wealthville-pool-scoring","Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter\u002FHold\u002FExit\u002FReduce\u002FAvoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-data\u002Fwealthville-pool-scoring\u002FSKILL.md",[116],{"categoryNo":117,"categoryName":118,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139],"scoring","pool","wealthville pool scoring","liquidity","which","for","exit","now","use","when","reduce","with","record","track","verdict","evm","solana","how","public","look",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":147,"publishedAt":52},"01M70MB6VR8ERJ4EM8D5KHBMEV","technical-debt-auditor","Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO\u002FFIXME\u002FHACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like \"where should I focus refactoring\", \"find code smells\", \"audit my codebase\", \"what technical debt do we have\", \"prioritize cleanup work\", or asks about code quality metrics. Also trigger when the user mentions \"code rot\", \"legacy cleanup\", \"refactoring priorities\", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say \"technical debt\" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Ftechnical-debt-auditor\u002FSKILL.md",[146],{"categoryNo":117,"categoryName":118,"taxonomyType":21,"taxonomyTypeDesc":22},[148,149,150,151,152,153,154,155,156,157,158,129,159,160,161,162,163,164,165,166],"technical debt","debt","technical","technical debt auditor","auditor","coverage","complexity","markers","project","cleanup","unused","code","todo","work","plan","focus","signals","audit","dependency",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":178,"publishedAt":52},"01M70KPYH9QNHCNME5GJQGE22K","readonly-sql-guard","Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production\u002FERP\u002Fanalytics database (a \"query\" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write\u002FDDL\u002Fside-effect\u002Ftransaction-escape risks. Checks what a statement CALLS, not just its shape.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdatabase\u002Freadonly-sql-guard\u002FSKILL.md",[173,174,175],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":117,"categoryName":118,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":176,"categoryName":177,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000033","数据分析师",[179,180,181,182,183,184,185,125,186,187,188,189,190,191,192,128,193,194,129,195],"readonly","guard","sql guard","sql","readonly sql guard","erp","effect","read-only","db","just","tool","calls","only","MCP","access","database","query",{"skillNo":197,"name":198,"nameZh":6,"description":199,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":200,"licenseFileUrl":201,"sourceHtmlUrl":202,"categories":203,"keywords":207,"publishedAt":52},"01M6AFY6F7CC2BBZP1QD6VTNVC","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[204],{"categoryNo":205,"categoryName":206,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,125,230],"artifacts builder","web","web artifacts builder","artifacts","builder","state","routing","state management","component","css","frontend","ui","Tools","file","components","shadcn","react","Tailwind","suite","jsx","html","single-file","ui components",{"skillNo":232,"name":233,"nameZh":6,"description":234,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":200,"licenseFileUrl":235,"sourceHtmlUrl":236,"categories":237,"keywords":242,"publishedAt":52},"01M6AFWF33SFV9Z3SF4PEEE4BF","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[238,241],{"categoryNo":239,"categoryName":240,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":205,"categoryName":206,"taxonomyType":21,"taxonomyTypeDesc":22},[243,244,245,246,247,209,248,218,219,249,250,251,252,125,253,131,254],"webapp testing","testing","webapp","browser","playwright","applications","debugging","toolkit","logs","screenshots","local","behavior",{"skillNo":256,"name":257,"nameZh":6,"description":258,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":200,"licenseFileUrl":259,"sourceHtmlUrl":260,"categories":261,"keywords":269,"publishedAt":52},"01M6AF67Q67JJJ5V51JR2P52KA","discernment-nudge","After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FSKILL.md",[262,265,266],{"categoryNo":263,"categoryName":264,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":117,"categoryName":118,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":267,"categoryName":268,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000036","内容创作者",[270,271,272,273,274,275,276,277,211,278,221,159,279,280,281,282,283,191,284,129,285,286,287,288,289,137,290],"discernment nudge","nudge","interpretation","help","run","reasoning","data","writing","lookup","content","review","conversation","short","up","invoke","you","analysis","claims","argument","assemble","recommendations"]