Agent Skill
2/7/2026

security-patterns

Reusable security implementation patterns and best practices for secure coding across all domains including Web2, Web3, and infrastructure components.

E
eccker
0GitHub Stars
1Views
npx skills add eccker/devagents

SKILL.md

Namesecurity-patterns
DescriptionReusable security implementation patterns and best practices for secure coding across all domains including Web2, Web3, and infrastructure components.

name: security-patterns description: Reusable security implementation patterns and best practices for secure coding across all domains including Web2, Web3, and infrastructure components.

Security Patterns Skill

This skill provides proven security implementation patterns and best practices for building secure software across traditional and blockchain domains.

Core Security Principles

1. Defense in Depth

  • Multiple layers of security controls
  • Fail-safe defaults and least privilege
  • Input validation at all boundaries

2. Secure by Design

  • Security considerations integrated from the start
  • Threat modeling for all new features
  • Regular security reviews and audits

Implementation Patterns

Input Validation Pattern

// Comprehensive input validation with sanitization
function validateAndSanitizeUserInput(input: unknown): string {
  if (typeof input !== 'string') {
    throw new SecurityError('Input must be a string');
  }
  
  // Length validation
  if (input.length > MAX_INPUT_LENGTH) {
    throw new SecurityError('Input exceeds maximum length');
  }
  
  // XSS prevention
  const sanitizedInput = sanitizeHtml(input, ALLOWED_TAGS);
  
  // SQL injection prevention (use parameterized queries)
  return sanitizedInput;
}

Authentication Pattern

// Secure authentication with JWT
function authenticateRequest(request: Request): AuthenticatedUser {
  const authHeader = request.headers.authorization;
  
  if (!authHeader?.startsWith('Bearer ')) {
    throw new UnauthorizedError('Missing or invalid authorization header');
  }
  
  const token = authHeader.substring(7);
  const decodedToken = verifyJwtToken(token, JWT_SECRET);
  
  return {
    userId: decodedToken.sub,
    permissions: decodedToken.permissions,
    expiresAt: decodedToken.exp
  };
}

Secrets Management Pattern

// Secure secrets handling
class SecretsManager {
  private static instance: SecretsManager;
  
  private constructor() {
    // Secrets never stored in code
    // Always retrieved from secure vault
  }
  
  async getSecret(secretName: string): Promise<string> {
    // Retrieve from AWS Secrets Manager, HashiCorp Vault, etc.
    const secret = await this.vaultClient.getSecret(secretName);
    
    // Log access for audit trail (without exposing value)
    this.auditLogger.logSecretAccess(secretName, getCurrentUser());
    
    return secret;
  }
}

Smart Contract Security Patterns

Checks-Effects-Interactions Pattern

// Prevent reentrancy attacks
contract SecureContract {
    mapping(address => uint256) private balances;
    
    function withdraw(uint256 amount) external {
        // Checks
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        // Effects (update state before external calls)
        balances[msg.sender] -= amount;
        
        // Interactions (external calls last)
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
}

Access Control Pattern

// Secure role-based access control
contract AccessControlled {
    using AccessControl for AccessControl.Role;
    
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
    
    modifier onlyRole(bytes32 role) {
        require(hasRole(role, msg.sender), "Access denied");
        _;
    }
    
    function criticalOperation() external onlyRole(ADMIN_ROLE) {
        // Only admins can execute this
    }
}

Security Testing Patterns

Security Test Cases

describe('Security Tests', () => {
  test('should prevent SQL injection attacks', async () => {
    const maliciousInput = "'; DROP TABLE users; --";
    
    await expect(
      userService.findUser(maliciousInput)
    ).rejects.toThrow('Invalid input detected');
  });
  
  test('should prevent XSS attacks', async () => {
    const maliciousScript = '<script>alert("xss")</script>';
    
    const sanitizedOutput = sanitizeUserInput(maliciousScript);
    expect(sanitizedOutput).not.toContain('<script>');
  });
});

Security Checklist

Pre-deployment Security Review

  • Input validation implemented at all entry points
  • Authentication and authorization properly configured
  • Secrets management using secure vault
  • HTTPS/TLS properly configured
  • SQL injection prevention (parameterized queries)
  • XSS prevention (output encoding/sanitization)
  • CSRF protection implemented
  • Rate limiting and DoS protection
  • Security headers configured
  • Dependency vulnerabilities scanned and resolved

Smart Contract Specific

  • Reentrancy protection implemented
  • Access control properly configured
  • Integer overflow/underflow protection
  • Gas optimization without security compromise
  • Oracle manipulation resistance
  • Front-running/MEV protection considered
  • Emergency pause functionality
  • Upgrade mechanism secured (if applicable)

Emergency Response

Security Incident Response Pattern

class SecurityIncidentResponse {
  async handleSecurityIncident(incident: SecurityIncident): Promise<void> {
    // 1. Immediate containment
    await this.enableEmergencyMode();
    
    // 2. Assessment and logging
    await this.logSecurityIncident(incident);
    
    // 3. Notification
    await this.notifySecurityTeam(incident);
    
    // 4. Evidence preservation
    await this.preserveEvidence(incident);
    
    // 5. Begin remediation
    await this.beginRemediation(incident);
  }
}
Skills Info
Original Name:security-patternsAuthor:eccker