security-practices
OWASP Top 10, authentication, and secure coding practices
What this skill does
# Security Practices
## Overview
Essential security practices for application development. Covers OWASP Top 10 and secure coding guidelines.
---
## OWASP Top 10
### 1. Injection (SQL, NoSQL, Command)
```typescript
// ❌ SQL Injection vulnerable
const query = `SELECT * FROM users WHERE email = '${email}'`;
// Attack: email = "'; DROP TABLE users; --"
// ✅ Parameterized query
const result = await db.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
// ✅ ORM with parameterization
const user = await prisma.user.findUnique({
where: { email }
});
// ❌ Command injection vulnerable
exec(`ping ${userInput}`);
// Attack: userInput = "google.com; rm -rf /"
// ✅ Use arrays, not string concatenation
execFile('ping', ['-c', '4', hostname]);
```
### 2. Broken Authentication
```typescript
// Strong password requirements
const passwordSchema = z.string()
.min(12)
.regex(/[A-Z]/, 'Must contain uppercase')
.regex(/[a-z]/, 'Must contain lowercase')
.regex(/[0-9]/, 'Must contain number')
.regex(/[^A-Za-z0-9]/, 'Must contain special character');
// Secure password hashing
import argon2 from 'argon2';
async function hashPassword(password: string): Promise<string> {
return argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536, // 64 MB
timeCost: 3,
parallelism: 4
});
}
async function verifyPassword(hash: string, password: string): Promise<boolean> {
return argon2.verify(hash, password);
}
// Rate limiting login attempts
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: 'Too many login attempts'
});
app.post('/login', loginLimiter, handleLogin);
```
### 3. Cross-Site Scripting (XSS)
```typescript
// ❌ Direct HTML insertion
element.innerHTML = userInput;
// Attack: userInput = "<script>stealCookies()</script>"
// ✅ Use textContent for text
element.textContent = userInput;
// ✅ React auto-escapes by default
function UserName({ name }: { name: string }) {
return <span>{name}</span>; // Safe
}
// ⚠️ dangerouslySetInnerHTML requires sanitization
import DOMPurify from 'dompurify';
function RichContent({ html }: { html: string }) {
const sanitized = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
ALLOWED_ATTR: ['href']
});
return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
}
// Content Security Policy header
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:;"
);
next();
});
```
### 4. Insecure Direct Object References
```typescript
// ❌ No authorization check
app.get('/api/documents/:id', async (req, res) => {
const doc = await db.documents.findById(req.params.id);
res.json(doc);
});
// Attack: User can access any document by guessing ID
// ✅ Verify ownership
app.get('/api/documents/:id', auth, async (req, res) => {
const doc = await db.documents.findById(req.params.id);
if (!doc) {
return res.status(404).json({ error: 'Not found' });
}
if (doc.ownerId !== req.user.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
res.json(doc);
});
// ✅ Use UUIDs instead of sequential IDs
// Harder to guess, but still check authorization!
const docId = crypto.randomUUID();
```
### 5. Cross-Site Request Forgery (CSRF)
```typescript
// CSRF token middleware
import csrf from 'csurf';
const csrfProtection = csrf({ cookie: true });
app.get('/form', csrfProtection, (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});
app.post('/submit', csrfProtection, (req, res) => {
// Token automatically validated
// ...
});
// In form
<form action="/submit" method="POST">
<input type="hidden" name="_csrf" value="{{csrfToken}}" />
<!-- form fields -->
</form>
// SameSite cookies
res.cookie('sessionId', token, {
httpOnly: true,
secure: true,
sameSite: 'strict' // or 'lax'
});
```
---
## Authentication
### JWT Best Practices
```typescript
import jwt from 'jsonwebtoken';
// Access token (short-lived)
function generateAccessToken(user: User): string {
return jwt.sign(
{ sub: user.id, role: user.role },
process.env.JWT_SECRET!,
{ expiresIn: '15m' }
);
}
// Refresh token (long-lived, stored securely)
function generateRefreshToken(user: User): string {
const token = jwt.sign(
{ sub: user.id, type: 'refresh' },
process.env.JWT_REFRESH_SECRET!,
{ expiresIn: '7d' }
);
// Store in database to allow revocation
db.refreshTokens.create({
userId: user.id,
token: hashToken(token),
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
});
return token;
}
// Verify and refresh
async function refreshAccessToken(refreshToken: string) {
const payload = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET!);
// Check if token is revoked
const storedToken = await db.refreshTokens.findOne({
userId: payload.sub,
token: hashToken(refreshToken)
});
if (!storedToken) {
throw new Error('Token revoked');
}
const user = await db.users.findById(payload.sub);
return generateAccessToken(user);
}
```
### OAuth 2.0 / OIDC
```typescript
import { OAuth2Client } from 'google-auth-library';
const client = new OAuth2Client(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
'https://myapp.com/auth/google/callback'
);
// Generate auth URL
app.get('/auth/google', (req, res) => {
const url = client.generateAuthUrl({
scope: ['openid', 'email', 'profile'],
state: generateState(req.session.id) // CSRF protection
});
res.redirect(url);
});
// Handle callback
app.get('/auth/google/callback', async (req, res) => {
const { code, state } = req.query;
// Verify state
if (!verifyState(state, req.session.id)) {
return res.status(400).send('Invalid state');
}
// Exchange code for tokens
const { tokens } = await client.getToken(code);
// Verify ID token
const ticket = await client.verifyIdToken({
idToken: tokens.id_token,
audience: process.env.GOOGLE_CLIENT_ID
});
const payload = ticket.getPayload();
// Create or update user
const user = await upsertUser({
email: payload.email,
name: payload.name,
picture: payload.picture
});
// Create session
req.session.userId = user.id;
res.redirect('/dashboard');
});
```
---
## Authorization
### Role-Based Access Control (RBAC)
```typescript
// Define permissions
const PERMISSIONS = {
admin: ['read', 'write', 'delete', 'admin'],
editor: ['read', 'write'],
viewer: ['read']
} as const;
// Middleware
function requirePermission(permission: string) {
return (req: Request, res: Response, next: NextFunction) => {
const userPermissions = PERMISSIONS[req.user.role] || [];
if (!userPermissions.includes(permission)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Usage
app.delete('/api/posts/:id', auth, requirePermission('delete'), deletePost);
```
### Attribute-Based Access Control (ABAC)
```typescript
interface Policy {
effect: 'allow' | 'deny';
resource: string;
action: string;
condition?: (context: Context) => boolean;
}
const policies: Policy[] = [
{
effect: 'allow',
resource: 'document',
action: 'read',
condition: (ctx) => ctx.resource.isPublic || ctx.user.id === ctx.resource.ownerId
},
{
effect: 'allow',
resource: 'document',
action: 'write',
condition: (ctx) => ctx.user.id === ctx.resource.ownerId
},
{
effect: 'allow',
resource: '*',
action: '*',
condition: (ctx) => ctx.user.role === 'admin'
}
];
function isAllowed(user: User, action: string, resource: Resource): boolean {
const context = { user, resource };
for (const policy of policies) {
if (
(policy.resource === '*' || policy.resource === resource.type) &&
(Related in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.