Secure Code Guardian
Core Workflow
- Threat model — Identify attack surface and threats
- Design — Plan security controls
- Implement — Write secure code with defense in depth; see code examples below
- Validate — Test security controls with explicit checkpoints (see below)
- Document — Record security decisions
Validation Checkpoints
After each implementation step, verify:
- Authentication: Test brute-force protection (lockout/rate limit triggers), session fixation resistance, token expiration, and invalid-credential error messages (must not leak user existence).
- Authorization: Verify horizontal and vertical privilege escalation paths are blocked; test with tokens belonging to different roles/users.
- Input handling: Confirm SQL injection payloads (
' OR 1=1--) are rejected; confirm XSS payloads (<script>alert(1)</script>) are escaped or rejected.
- Headers/CORS: Validate with a security scanner (e.g.,
curl -I, Mozilla Observatory) that security headers are present and CORS origin allowlist is correct.
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| OWASP |
references/owasp-prevention.md |
OWASP Top 10 patterns |
| Authentication |
references/authentication.md |
Password hashing, JWT |
| Input Validation |
references/input-validation.md |
Zod, SQL injection |
| XSS/CSRF |
references/xss-csrf.md |
XSS prevention, CSRF |
| Headers |
references/security-headers.md |
Helmet, rate limiting |
Constraints
MUST DO
- Hash passwords with bcrypt/argon2 (never MD5/SHA-1/unsalted hashes)
- Use parameterized queries (never string-interpolated SQL)
- Validate and sanitize all user input before use
- Implement rate limiting on auth endpoints
- Set security headers (CSP, HSTS, X-Frame-Options)
- Log security events (failed auth, privilege escalation attempts)
- Store secrets in environment variables or secret managers (never in source code)
MUST NOT DO
- Store passwords in plaintext or reversibly encrypted form
- Trust user input without validation
- Expose sensitive data in logs or error responses
- Use weak or deprecated algorithms (MD5, SHA-1, DES, ECB mode)
- Hardcode secrets or credentials in code
Code Examples
Password Hashing (bcrypt)
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12; // minimum 10; 12 balances security and performance
export async function hashPassword(plaintext: string): Promise<string> {
return bcrypt.hash(plaintext, SALT_ROUNDS);
}
export async function verifyPassword(plaintext: string, hash: string): Promise<boolean> {
return bcrypt.compare(plaintext, hash);
}
Parameterized SQL Query (Node.js / pg)
// NEVER: `SELECT * FROM users WHERE email = '${email}'`
// ALWAYS: use positional parameters
import { Pool } from 'pg';
const pool = new Pool();
export async function getUserByEmail(email: string) {
const { rows } = await pool.query(
'SELECT id, email, role FROM users WHERE email = $1',
[email] // value passed separately — never interpolated
);
return rows[0] ?? null;
}
Input Validation with Zod
import { z } from 'zod';
const LoginSchema = z.object({
email: z.string().email().max(254),
password: z.string().min(8).max(128),
});
export function validateLoginInput(raw: unknown) {
const result = LoginSchema.safeParse(raw);
if (!result.success) {
// Return generic error — never echo raw input back
throw new Error('Invalid credentials format');
}
return result.data;
}
JWT Validation
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET!; // never hardcode
export function verifyToken(token: string): jwt.JwtPayload {
// Throws if expired, tampered, or wrong algorithm
const payload = jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'], // explicitly allowlist algorithm
issuer: 'your-app',
audience: 'your-app',
});
if (typeof payload === 'string') throw new Error('Invalid token payload');
return payload;
}
Securing an Endpoint — Full Flow
import express from 'express';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
const app = express();
app.use(helmet()); // sets CSP, HSTS, X-Frame-Options, etc.
app.use(express.json({ limit: '10kb' })); // limit payload size
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // 10 attempts per window per IP
standardHeaders: true,
legacyHeaders: false,
});
app.post('/api/login', authLimiter, async (req, res) => {
// 1. Validate input
const { email, password } = validateLoginInput(req.body);
// 2. Authenticate — parameterized query, constant-time compare
const user = await getUserByEmail(email);
if (!user || !(await verifyPassword(password, user.passwordHash))) {
// Generic message — do not reveal whether email exists
return res.status(401).json({ error: 'Invalid credentials' });
}
// 3. Authorize — issue scoped, short-lived token
const token = jwt.sign(
{ sub: user.id, role: user.role },
JWT_SECRET,
{ algorithm: 'HS256', expiresIn: '15m', issuer: 'your-app', audience: 'your-app' }
);
// 4. Secure response — token in httpOnly cookie, not body
res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'strict' });
return res.json({ message: 'Authenticated' });
});
Output Templates
When implementing security features, provide:
- Secure implementation code
- Security considerations noted
- Configuration requirements (env vars, headers)
- Testing recommendations
Knowledge Reference
OWASP Top 10, bcrypt/argon2, JWT, OAuth 2.0, OIDC, CSP, CORS, rate limiting, input validation, output encoding, encryption (AES, RSA), TLS, security headers
1---
2name: secure-code-guardian
3description: Use when implementing authentication/authorization, securing user input, or preventing OWASP Top 10 vulnerabilities — including custom security implementations such as hashing passwords with bcrypt/argon2, sanitizing SQL queries with parameterized statements, configuring CORS/CSP headers, validating input with Zod, and setting up JWT tokens. Invoke for authentication, authorization, input validation, encryption, OWASP Top 10 prevention, secure session management, and security hardening. For pre-built OAuth/SSO integrations or standalone security audits, consider a more specialized skill.
4license: MIT
5metadata:
6 source: https://skillmd.com/skills/aibot88/secure-code-guardian
7 author: https://github.com/Jeffallan
8 version: "1.1.0"
9 domain: security
10 triggers: security, authentication, authorization, encryption, OWASP, vulnerability, secure coding, password, JWT, OAuth
11 role: specialist
12 scope: implementation
13 output-format: code
14 related-skills: fullstack-guardian, security-reviewer, architecture-designer
15---
16
17# Secure Code Guardian
18
19## Core Workflow
20
211. **Threat model** — Identify attack surface and threats
222. **Design** — Plan security controls
233. **Implement** — Write secure code with defense in depth; see code examples below
244. **Validate** — Test security controls with explicit checkpoints (see below)
255. **Document** — Record security decisions
26
27### Validation Checkpoints
28
29After each implementation step, verify:
30
31- **Authentication**: Test brute-force protection (lockout/rate limit triggers), session fixation resistance, token expiration, and invalid-credential error messages (must not leak user existence).
32- **Authorization**: Verify horizontal and vertical privilege escalation paths are blocked; test with tokens belonging to different roles/users.
33- **Input handling**: Confirm SQL injection payloads (`' OR 1=1--`) are rejected; confirm XSS payloads (`<script>alert(1)</script>`) are escaped or rejected.
34- **Headers/CORS**: Validate with a security scanner (e.g., `curl -I`, Mozilla Observatory) that security headers are present and CORS origin allowlist is correct.
35
36## Reference Guide
37
38Load detailed guidance based on context:
39
40| Topic | Reference | Load When |
41|-------|-----------|-----------|
42| OWASP | `references/owasp-prevention.md` | OWASP Top 10 patterns |
43| Authentication | `references/authentication.md` | Password hashing, JWT |
44| Input Validation | `references/input-validation.md` | Zod, SQL injection |
45| XSS/CSRF | `references/xss-csrf.md` | XSS prevention, CSRF |
46| Headers | `references/security-headers.md` | Helmet, rate limiting |
47
48## Constraints
49
50### MUST DO
51- Hash passwords with bcrypt/argon2 (never MD5/SHA-1/unsalted hashes)
52- Use parameterized queries (never string-interpolated SQL)
53- Validate and sanitize all user input before use
54- Implement rate limiting on auth endpoints
55- Set security headers (CSP, HSTS, X-Frame-Options)
56- Log security events (failed auth, privilege escalation attempts)
57- Store secrets in environment variables or secret managers (never in source code)
58
59### MUST NOT DO
60- Store passwords in plaintext or reversibly encrypted form
61- Trust user input without validation
62- Expose sensitive data in logs or error responses
63- Use weak or deprecated algorithms (MD5, SHA-1, DES, ECB mode)
64- Hardcode secrets or credentials in code
65
66## Code Examples
67
68### Password Hashing (bcrypt)
69
70```typescript
71import bcrypt from 'bcrypt';
72
73const SALT_ROUNDS = 12; // minimum 10; 12 balances security and performance
74
75export async function hashPassword(plaintext: string): Promise<string> {
76 return bcrypt.hash(plaintext, SALT_ROUNDS);
77}
78
79export async function verifyPassword(plaintext: string, hash: string): Promise<boolean> {
80 return bcrypt.compare(plaintext, hash);
81}
82```
83
84### Parameterized SQL Query (Node.js / pg)
85
86```typescript
87// NEVER: `SELECT * FROM users WHERE email = '${email}'`
88// ALWAYS: use positional parameters
89import { Pool } from 'pg';
90const pool = new Pool();
91
92export async function getUserByEmail(email: string) {
93 const { rows } = await pool.query(
94 'SELECT id, email, role FROM users WHERE email = $1',
95 [email] // value passed separately — never interpolated
96 );
97 return rows[0] ?? null;
98}
99```
100
101### Input Validation with Zod
102
103```typescript
104import { z } from 'zod';
105
106const LoginSchema = z.object({
107 email: z.string().email().max(254),
108 password: z.string().min(8).max(128),
109});
110
111export function validateLoginInput(raw: unknown) {
112 const result = LoginSchema.safeParse(raw);
113 if (!result.success) {
114 // Return generic error — never echo raw input back
115 throw new Error('Invalid credentials format');
116 }
117 return result.data;
118}
119```
120
121### JWT Validation
122
123```typescript
124import jwt from 'jsonwebtoken';
125
126const JWT_SECRET = process.env.JWT_SECRET!; // never hardcode
127
128export function verifyToken(token: string): jwt.JwtPayload {
129 // Throws if expired, tampered, or wrong algorithm
130 const payload = jwt.verify(token, JWT_SECRET, {
131 algorithms: ['HS256'], // explicitly allowlist algorithm
132 issuer: 'your-app',
133 audience: 'your-app',
134 });
135 if (typeof payload === 'string') throw new Error('Invalid token payload');
136 return payload;
137}
138```
139
140### Securing an Endpoint — Full Flow
141
142```typescript
143import express from 'express';
144import rateLimit from 'express-rate-limit';
145import helmet from 'helmet';
146
147const app = express();
148app.use(helmet()); // sets CSP, HSTS, X-Frame-Options, etc.
149app.use(express.json({ limit: '10kb' })); // limit payload size
150
151const authLimiter = rateLimit({
152 windowMs: 15 * 60 * 1000, // 15 minutes
153 max: 10, // 10 attempts per window per IP
154 standardHeaders: true,
155 legacyHeaders: false,
156});
157
158app.post('/api/login', authLimiter, async (req, res) => {
159 // 1. Validate input
160 const { email, password } = validateLoginInput(req.body);
161
162 // 2. Authenticate — parameterized query, constant-time compare
163 const user = await getUserByEmail(email);
164 if (!user || !(await verifyPassword(password, user.passwordHash))) {
165 // Generic message — do not reveal whether email exists
166 return res.status(401).json({ error: 'Invalid credentials' });
167 }
168
169 // 3. Authorize — issue scoped, short-lived token
170 const token = jwt.sign(
171 { sub: user.id, role: user.role },
172 JWT_SECRET,
173 { algorithm: 'HS256', expiresIn: '15m', issuer: 'your-app', audience: 'your-app' }
174 );
175
176 // 4. Secure response — token in httpOnly cookie, not body
177 res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'strict' });
178 return res.json({ message: 'Authenticated' });
179});
180```
181
182## Output Templates
183
184When implementing security features, provide:
1851. Secure implementation code
1862. Security considerations noted
1873. Configuration requirements (env vars, headers)
1884. Testing recommendations
189
190## Knowledge Reference
191
192OWASP Top 10, bcrypt/argon2, JWT, OAuth 2.0, OIDC, CSP, CORS, rate limiting, input validation, output encoding, encryption (AES, RSA), TLS, security headers