К основному содержанию
скилл CX Codex

secure-coding-practices — скилл для Claude Code: защита кода

Скилл secure-coding-practices для Claude Code помогает применять защитные практики при работе с авторизацией, пользовательским вводом и чувствительными данными. Подключается и для проверки кода на уязвимости.

MIT 134 установок ★ 71 обновлён 2026-06-29

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add NickCrew/Claude-Cortex --skill secure-coding-practices -a claude-code
Открыть на GitHub

Что делает secure-coding-practices

Скилл подсказывает, как проверять входные данные, кодировать вывод и настраивать контроль доступа. Для отдельных задач он содержит справочные файлы об аутентификации, криптографии, зависимостях, обработке ошибок и безопасных настройках.

При проверке кода он обращает внимание на небезопасные SQL-запросы, пути из пользовательского ввода, жёстко заданные секреты и слабую криптографию. Также описаны принципы минимальных привилегий и безопасного поведения при ошибках. Скилл активируется для файлов с secret в имени, а также в каталогах auth и security.

Какие задачи решает

  • проверить обработку пользовательского ввода
  • найти небезопасные SQL-запросы
  • оценить настройки аутентификации и сессий
  • обнаружить секреты, записанные в коде

Примеры запросов агенту

  • Проверь этот код на проблемы безопасности и перечисли рискованные места.
  • Помоги безопасно обработать пользовательский ввод в этом API.
  • Проведи проверку аутентификации и управления сессиями.

Как установить secure-coding-practices

1Через Skills CLI (Vercel)

npx skills add NickCrew/Claude-Cortex --skill secure-coding-practices -a claude-code

2Вручную: положить файлы

~/.claude/skills/secure-coding-practices/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/secure-coding-practices/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о secure-coding-practices

Как установить secure-coding-practices в Claude Code?

Выполните npx skills add NickCrew/Claude-Cortex --skill secure-coding-practices -a claude-code. Файл скилла находится по пути ~/.claude/skills/secure-coding-practices/SKILL.md.

Что делает secure-coding-practices?

Скилл помогает применять защитные практики в коде и искать распространённые риски при проверке безопасности.

В каких случаях подключается secure-coding-practices?

Он используется при работе с аутентификацией, пользовательским вводом и чувствительными данными, а также во время проверки кода на безопасность.

Исходный текст

SKILL.md · MIT
---
name: secure-coding-practices
description: Secure coding practices and defensive programming patterns for building security-first applications. Use when implementing authentication, handling user input, managing sensitive data, or conducting secure code reviews.
keywords:
  - code security
  - defense in depth
  - input validation
  - least privilege
  - output encoding
  - sanitization
  - secure by design
  - secure coding
  - security hardening
  - threat modeling
file_patterns:
  - '**/*secret*.py'
  - '**/*secret*.ts'
  - '**/auth/**'
  - '**/security/**'
confidence: 0.87
---

# Secure Coding Practices

Comprehensive guidance for implementing security-first development patterns with defensive programming techniques and proactive threat mitigation strategies.

## When to Use This Skill

- Implementing authentication and authorization systems
- Processing user input or external data
- Handling sensitive data (PII, credentials, financial information)
- Building APIs and web services
- Managing cryptographic operations (hashing, encryption)
- Conducting security-focused code reviews
- Establishing secure development standards for teams
- Evaluating third-party dependencies and libraries
- Designing error handling and logging strategies
- Implementing session management and token handling

## Core Security Principles

### Defense in Depth
Apply multiple layers of security controls - never rely on a single protection mechanism.

### Fail Securely
When errors occur, default to the secure state (deny access, reject input, log event).

### Least Privilege
Grant minimum necessary permissions - users, services, and databases should have only required access.

### Trust Nothing
Validate all input, encode all output, verify all sources, authenticate all requests.

## Quick Reference

| Task | Load reference |
| --- | --- |
| Input validation & sanitization | `skills/secure-coding-practices/references/input-validation.md` |
| Output encoding & XSS prevention | `skills/secure-coding-practices/references/output-encoding.md` |
| Authentication & sessions | `skills/secure-coding-practices/references/authentication.md` |
| Cryptography & key management | `skills/secure-coding-practices/references/cryptography.md` |
| Dependencies & supply chain | `skills/secure-coding-practices/references/dependencies.md` |
| Error handling & logging | `skills/secure-coding-practices/references/error-handling.md` |
| Secure defaults & configuration | `skills/secure-coding-practices/references/secure-defaults.md` |

## Workflow

1. **Identify security requirements** - Authentication, authorization, data protection, compliance
2. **Load relevant references** - Use Quick Reference table to find specific guidance
3. **Implement security controls** - Apply patterns from references with proper context
4. **Validate implementation** - Test with security scanners, penetration testing, code review
5. **Monitor and maintain** - Regular security audits, dependency updates, vulnerability scanning

## Security Checklist

**Input Validation:**
- [ ] Validate all user input server-side with allowlists
- [ ] Use schema validation libraries (Joi, Yup, Zod)
- [ ] Implement strict type checking
- [ ] Sanitize file paths and prevent traversal

**Output Encoding:**
- [ ] Apply context-aware encoding (HTML, JS, URL, SQL)
- [ ] Use templating engines with auto-escaping
- [ ] Implement Content Security Policy (CSP)
- [ ] Set secure HTTP headers (Helmet.js)

**Authentication & Authorization:**
- [ ] Hash passwords with bcrypt/Argon2 (salt rounds ≥12)
- [ ] Implement secure session management
- [ ] Use HTTPS-only cookies with HttpOnly and SameSite
- [ ] Apply rate limiting on authentication endpoints
- [ ] Verify authorization on every request

**Cryptography:**
- [ ] Use AES-256-GCM for encryption
- [ ] Generate keys with crypto.randomBytes()
- [ ] Store secrets in environment variables or KMS
- [ ] Never roll your own crypto

**Dependencies:**
- [ ] Run npm audit regularly
- [ ] Lock dependency versions in package.json
- [ ] Use Snyk/Dependabot for monitoring
- [ ] Verify package integrity (SRI for CDN)

**Error Handling & Logging:**
- [ ] Return generic error messages to users
- [ ] Log errors with correlation IDs
- [ ] Never log passwords, tokens, or PII
- [ ] Monitor security events and alerts

## Common Mistakes

- Using client-side validation as sole defense (always validate server-side)
- Blocklisting instead of allowlisting (define what's allowed, not forbidden)
- Exposing stack traces or internal errors to users
- Hardcoding secrets in source code
- Using Math.random() for security-critical operations
- Not implementing rate limiting on authentication endpoints
- Loose equality comparisons allowing type coercion attacks
- Trusting user input in database queries (SQL injection)
- Missing output encoding based on context (XSS vulnerabilities)
- Insufficient password hashing (weak algorithms or low work factor)

## High-Risk Code Patterns

Watch for these patterns in code reviews:
1. String concatenation in SQL queries (injection risk)
2. Direct file path construction from user input (traversal risk)
3. eval(), Function(), or exec() with user input (code injection)
4. Deserialization of untrusted data (RCE risk)
5. Hardcoded secrets or credentials (exposure risk)
6. Missing authentication/authorization checks (access control)
7. Weak cryptography (MD5, SHA1, ECB mode)
8. Verbose error messages in production (information disclosure)
9. Missing input validation (injection, DoS)
10. Insecure session configuration (hijacking risk)

## Resources

**OWASP Resources:**
- **OWASP Top 10**: https://owasp.org/Top10/
- **OWASP Cheat Sheet Series**: https://cheatsheetseries.owasp.org/
- **OWASP ASVS**: Application Security Verification Standard
- **OWASP Dependency-Check**: https://owasp.org/www-project-dependency-check/

**Standards & Guidelines:**
- **NIST Cybersecurity Framework**: https://www.nist.gov/cyberframework
- **NIST SP 800-63B**: Digital Identity Guidelines (Authentication)
- **CWE Top 25**: https://cwe.mitre.org/top25/

**Tools:**
- **SAST**: SonarQube, Semgrep, CodeQL
- **DAST**: OWASP ZAP, Burp Suite
- **SCA**: Snyk, npm audit, Dependabot
- **Secrets Detection**: TruffleHog, git-secrets

© NickCrew · MIT · NickCrew/Claude-Cortex

Похожие скиллы

Все скиллы по теме «Безопасность» →
netsuite-owasp-secure-coding Oracle NetSuite Скилл netsuite-owasp-secure-coding встраивает в ИИ-агента правила безопасной разработки по OWASP Top 10 (2021) для JavaScript и SuiteScript 2.1. Помогает находить уязвимости. CX Codex +1 873установок 124-java-secure-coding Juan Antonio Breña Moral Скилл 124-java-secure-coding для Claude Code помогает находить и устранять уязвимости в Java-коде. Запускается на запросы о проверке валидации, инъекций и обработки ошибок. CX Codex +1 491установок input-validation-sanitization-auditor patricio0312rev Скилл input-validation-sanitization-auditor находит и устраняет уязвимости XSS, SQL-инъекций и инъекций команд с помощью схем валидации и безопасных шаблонов кода. CX Codex +1 292установок Security Engineer daffy0208 Скилл Security Engineer для Claude Code проверяет безопасность API и приложения: аутентификацию, права доступа, ввод данных и конфигурацию в рамках security review. CX Codex +1 213установок backend-security-coder rmyndharis Скилл backend-security-coder для Claude Code помогает писать защищённый код бэкенда и проводить ревью безопасности. Включается для реализации проверок ввода, аутентификации и защиты API. CX Codex +1 142установок threat-mitigation-mapping Seth Hobson Скилл threat-mitigation-mapping для Claude Code связывает выявленные угрозы с мерами защиты и помогает составить план устранения рисков. Проверяет покрытие контролями. CX Codex +1 19 456установок

Из того же набора21

Весь набор →
helm-chart-patterns Скилл helm-chart-patterns для Claude Code описывает создание чартов Helm для Kubernetes: структуру шаблонов, проверку values.schema.json, хуки и настройки нескольких окружений. CX Codex +1 179установок typescript-advanced-patterns Скилл typescript-advanced-patterns для Claude Code проектирует сложные типы TypeScript — от брендированных идентификаторов до типобезопасных API. Выражает правила предметной области на уровне типов. CX Codex +1 174установок code-explanation Скилл code-explanation для Claude Code и Codex объясняет код, архитектуру и поведение систем с учётом уровня читателя. Помогает разбирать код, обучаться и передавать знания. CX Codex +1 173установок security-testing-patterns Скилл security-testing-patterns задаёт правила тестирования безопасности: от SAST и SCA до фаззинга, DAST и аудита API по OWASP. Помогает выстроить CI/CD пайплайн и разобрать уязвимости. CX Codex +1 154установок ux-review Скилл ux-review проверяет компонент или поток с трёх сторон: удобство, доступность по WCAG 2.1 AA и поведение интерфейса. Отдаёт отчёт с находками по приоритетам. CX Codex +1 119установок event-driven-architecture Скилл event-driven-architecture для Claude Code помогает проектировать системы на событиях: event sourcing, CQRS, саги и обмен сообщениями. Охватывает микросервисы и распределённые транзакции. CX Codex +1 118установок dashboard-designer Скилл dashboard-designer для Claude Code помогает спроектировать дашборд: выбрать KPI, расположить блоки и настроить визуальную иерархию. Запускается на запросы о структуре панели мониторинга или выборе BI-инструмента. CX Codex +1 109установок terraform-best-practices Скилл terraform-best-practices внедряет инженерные стандарты Terraform: разбиение на модули, блокировку стейта, разделение сред и валидацию в CI/CD. CX Codex +1 109установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой