PluginBench
Skill
Pass
Audit score 90

secure-code-guardian

jeffallan/claude-skills

Implement authentication, authorization, input validation, and OWASP Top 10 defenses with secure code patterns.

What is secure-code-guardian?

Secure Code Guardian guides you through threat modeling, designing security controls, and implementing custom authentication/authorization, password hashing, parameterized queries, input validation, JWT tokens, and security headers. Use it when building authentication systems, securing user input, preventing injection attacks, or hardening endpoints against common vulnerabilities.

  • Hash passwords with bcrypt/argon2 and verify securely
  • Execute parameterized SQL queries to prevent injection attacks
  • Validate and sanitize input with Zod schemas
  • Issue and verify JWT tokens with expiration and algorithm constraints
  • Configure security headers (CSP, HSTS, X-Frame-Options) via Helmet
  • Implement rate limiting on authentication endpoints

How to install secure-code-guardian

npx skills add https://github.com/jeffallan/claude-skills --skill secure-code-guardian
Prerequisites
  • Node.js/TypeScript environment
  • bcrypt or argon2 library installed
  • jsonwebtoken library for JWT handling
  • Zod or similar validation library
  • express-rate-limit and helmet for middleware
Claude Code
Cursor
Windsurf
Cline

How to use secure-code-guardian

  1. 1.Identify your threat model and attack surface for the feature you're building
  2. 2.Design security controls (authentication method, token strategy, rate limits)
  3. 3.Implement using the provided code examples: password hashing, parameterized queries, input validation, JWT, and security headers
  4. 4.Run validation checkpoints: test brute-force protection, privilege escalation paths, injection payloads, and header presence
  5. 5.Document security decisions and configuration requirements (environment variables, CORS origins)

Use cases

Good for
  • Building a login endpoint with password hashing, rate limiting, and JWT token issuance
  • Securing database queries against SQL injection using parameterized statements
  • Validating form input and API payloads to reject malformed or malicious data
  • Configuring CORS and security headers on an Express server
  • Implementing role-based authorization checks before sensitive operations
Who it's for
  • Backend developers implementing custom authentication systems
  • Full-stack engineers securing user-facing APIs
  • Security-conscious teams building from scratch rather than using pre-built OAuth providers
  • Developers hardening existing applications against injection and XSS attacks

secure-code-guardian FAQ

Should I use bcrypt or argon2 for password hashing?

Both are secure; bcrypt is simpler and widely supported (use SALT_ROUNDS ≥ 10). Argon2 is newer and memory-hard, better against GPU attacks. Choose bcrypt for simplicity unless you have specific performance constraints.

How do I prevent SQL injection?

Always use parameterized queries (e.g., `$1`, `$2` placeholders in pg) and pass values separately from the SQL string. Never interpolate user input directly into SQL.

What should I do if input validation fails?

Return a generic error message (e.g., 'Invalid credentials format') without echoing the raw input back. This prevents attackers from learning what payloads are accepted.

How long should JWT tokens be valid?

Use short expiration times (15 minutes for access tokens) and refresh tokens for longer sessions. Always verify expiration, algorithm, issuer, and audience on token validation.

Do I need to use OAuth/SSO, or can I implement custom authentication?

Custom authentication is fine for internal or low-risk applications. Use this skill for custom implementations. For public-facing apps or compliance requirements, consider a specialized OAuth/SSO skill.

Full instructions (SKILL.md)

Source of truth, from jeffallan/claude-skills.


name: secure-code-guardian description: 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. license: MIT metadata: author: https://github.com/Jeffallan version: "1.1.0" domain: security triggers: security, authentication, authorization, encryption, OWASP, vulnerability, secure coding, password, JWT, OAuth role: specialist scope: implementation output-format: code related-skills: fullstack-guardian, security-reviewer, architecture-designer

Secure Code Guardian

Core Workflow

  1. Threat model — Identify attack surface and threats
  2. Design — Plan security controls
  3. Implement — Write secure code with defense in depth; see code examples below
  4. Validate — Test security controls with explicit checkpoints (see below)
  5. 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:

TopicReferenceLoad When
OWASPreferences/owasp-prevention.mdOWASP Top 10 patterns
Authenticationreferences/authentication.mdPassword hashing, JWT
Input Validationreferences/input-validation.mdZod, SQL injection
XSS/CSRFreferences/xss-csrf.mdXSS prevention, CSRF
Headersreferences/security-headers.mdHelmet, 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:

  1. Secure implementation code
  2. Security considerations noted
  3. Configuration requirements (env vars, headers)
  4. 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

Documentation