Claude
Skills
Sign in
โ† Back

Security Engineer

Included with Lifetime
$97 forever

Implement security best practices across the application stack. Use when securing APIs, implementing authentication, preventing vulnerabilities, or conducting security reviews. Covers OWASP Top 10, auth patterns, input validation, encryption, and security monitoring.

Security

What this skill does


# Security Engineer

Security is not optional - build it in from day one.

## Core Principle

**Security is built-in, not bolted-on.**

Every feature, every endpoint, every data flow must consider security implications. Security vulnerabilities cost 10x more to fix in production than during development.

## 5 Security Pillars

### Pillar 1: Authentication & Authorization ๐Ÿ”

**Authentication:** Who are you?
**Authorization:** What can you do?

#### Authentication Strategies

**JWT (JSON Web Tokens):**

- **When:** Stateless APIs, mobile apps, microservices
- **How:** Sign tokens with secret, store in httpOnly cookies or Authorization header
- **Security:** Use RS256 (not HS256), short expiry (15min access, 7d refresh)

```typescript
// Example: Next.js API with JWT
import { SignJWT, jwtVerify } from 'jose'

const secret = new TextEncoder().encode(process.env.JWT_SECRET!)

export async function createToken(userId: string) {
  return await new SignJWT({ userId })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('15m')
    .sign(secret)
}

export async function verifyToken(token: string) {
  const { payload } = await jwtVerify(token, secret)
  return payload
}
```

**Session-Based:**

- **When:** Traditional web apps, server-side rendering
- **How:** Server stores session ID in encrypted cookie
- **Security:** HttpOnly, Secure, SameSite=Strict cookies

**OAuth 2.0 / OIDC:**

- **When:** Social login, third-party integrations
- **How:** Use NextAuth.js, Passport.js, or Auth0
- **Security:** Validate state parameter, use PKCE for mobile

#### Authorization Patterns

**RBAC (Role-Based Access Control):**

```typescript
// Define roles
enum Role {
  ADMIN = 'admin',
  USER = 'user',
  GUEST = 'guest'
}

// Check permissions
function requireRole(allowedRoles: Role[]) {
  return (req, res, next) => {
    if (!allowedRoles.includes(req.user.role)) {
      return res.status(403).json({ error: 'Forbidden' })
    }
    next()
  }
}

// Usage
app.delete('/api/users/:id', requireRole([Role.ADMIN]), deleteUser)
```

**ABAC (Attribute-Based):**

- More granular: user can edit resource if they created it
- Example: User can delete post only if post.authorId === user.id

**Key Principles:**

- โœ… Always verify authentication before authorization
- โœ… Default deny (whitelist, not blacklist)
- โœ… Check permissions on server, never trust client
- โœ… Re-verify permissions before critical actions

---

### Pillar 2: Input Validation & Sanitization ๐Ÿ›ก๏ธ

**Never trust user input** - validate, sanitize, escape everything.

#### Prevent SQL Injection

**โŒ Bad (Vulnerable):**

```javascript
// DON'T DO THIS!
const query = `SELECT * FROM users WHERE email = '${userInput}'`
db.query(query) // SQL injection vulnerability!
```

**โœ… Good (Parameterized Queries):**

```javascript
// Always use parameterized queries
const query = 'SELECT * FROM users WHERE email = ?'
db.query(query, [userInput]) // Safe - parameterized

// With Prisma
const user = await prisma.user.findUnique({
  where: { email: userInput } // Safe - ORM handles it
})
```

#### Prevent XSS (Cross-Site Scripting)

**โŒ Bad (Vulnerable):**

```jsx
// DON'T DO THIS!
<div dangerouslySetInnerHTML={{ __html: userInput }} />
```

**โœ… Good (Escaped):**

```jsx
// React automatically escapes
;<div>{userInput}</div> // Safe

// If you must render HTML, sanitize first
import DOMPurify from 'isomorphic-dompurify'
;<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />
```

#### Input Validation with Zod

```typescript
import { z } from 'zod'

const UserSchema = z.object({
  email: z.string().email().max(255),
  password: z.string().min(8).max(100),
  age: z.number().int().min(13).max(120),
  website: z.string().url().optional()
})

// Validate
const result = UserSchema.safeParse(req.body)
if (!result.success) {
  return res.status(400).json({ errors: result.error.issues })
}

const validData = result.data // Type-safe!
```

#### File Upload Security

```typescript
import multer from 'multer'

const upload = multer({
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB max
  },
  fileFilter: (req, file, cb) => {
    // Whitelist file types
    const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
    if (!allowedTypes.includes(file.mimetype)) {
      return cb(new Error('Invalid file type'))
    }
    cb(null, true)
  }
})

// Generate random filenames (don't trust user input)
const filename = crypto.randomUUID() + path.extname(file.originalname)
```

**Key Principles:**

- โœ… Validate on server (never trust client validation)
- โœ… Use schema validation libraries (Zod, Yup, Joi)
- โœ… Whitelist allowed values, don't blacklist
- โœ… Escape output based on context (HTML, URL, JS)

---

### Pillar 3: Secure Configuration ๐Ÿ”ง

#### Environment Variables

**Never commit secrets:**

```bash
# .env (add to .gitignore!)
DATABASE_URL="postgresql://user:pass@localhost:5432/db"
JWT_SECRET="generate-with-openssl-rand-base64-32"
OPENAI_API_KEY="sk-..."
```

**Access in code:**

```typescript
// Validate env vars on startup
if (!process.env.JWT_SECRET) {
  throw new Error('JWT_SECRET is required')
}

const config = {
  jwtSecret: process.env.JWT_SECRET,
  databaseUrl: process.env.DATABASE_URL
}
```

**Secret Management (Production):**

- AWS Secrets Manager
- Vercel Environment Variables
- HashiCorp Vault
- Doppler

#### Security Headers

```typescript
// Next.js middleware
export function middleware(request: NextRequest) {
  const response = NextResponse.next()

  // Prevent clickjacking
  response.headers.set('X-Frame-Options', 'DENY')

  // Prevent MIME sniffing
  response.headers.set('X-Content-Type-Options', 'nosniff')

  // XSS Protection
  response.headers.set('X-XSS-Protection', '1; mode=block')

  // Content Security Policy
  response.headers.set(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
  )

  // HTTPS only
  response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

  return response
}
```

#### CORS Configuration

```typescript
// Configure CORS properly
app.use(
  cors({
    origin:
      process.env.NODE_ENV === 'production' ? 'https://yourdomain.com' : 'http://localhost:3000',
    credentials: true, // Allow cookies
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
  })
)
```

**Key Principles:**

- โœ… Use environment variables for all secrets
- โœ… Different secrets per environment (dev, staging, prod)
- โœ… Rotate secrets regularly
- โœ… Set security headers on all responses
- โœ… Configure CORS restrictively

---

### Pillar 4: Data Protection ๐Ÿ”’

#### Password Hashing

**โŒ Never store passwords in plain text or use MD5/SHA1!**

**โœ… Use bcrypt or argon2:**

```typescript
import bcrypt from 'bcrypt'

// Hash password (on signup)
const saltRounds = 12
const hashedPassword = await bcrypt.hash(password, saltRounds)
await db.user.create({
  email,
  password: hashedPassword // Store hash, never plain text
})

// Verify password (on login)
const user = await db.user.findUnique({ where: { email } })
const isValid = await bcrypt.compare(password, user.password)
if (!isValid) {
  throw new Error('Invalid credentials')
}
```

#### Encryption at Rest

**Sensitive data should be encrypted:**

```typescript
import crypto from 'crypto'

const algorithm = 'aes-256-gcm'
const key = Buffer.from(process.env.ENCRYPTION_KEY!, 'hex')

function encrypt(text: string) {
  const iv = crypto.randomBytes(16)
  const cipher = crypto.createCipheriv(algorithm, key, iv)
  const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()])
  const authTag = cipher.getAuthTag()
  return {
    iv: iv.toString('hex'),
    encryptedData: encrypted.toString('hex'),
    authTag: authTag.toString('hex')
  }
}

function decrypt(encrypted: any) {
  const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(encrypted.iv, 'hex'))
  decipher.setAuthTag(Buffer.from

Related in Security