Логотип Py Security

Py Security

Сообщество
l-mb
py-security

Security vulnerability detection and remediation for Python codebases. Identifies SQL injection, hardcoded secrets, weak cryptography, and other OWASP vulnerabilities.

Add to TypingMind

Обзор

Издательl-mb
Репозиторийpython-refactoring-skills
Название навыкаpy-security
Звёзды
57
Форки
1
Файлы в комплекте
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — l-mb. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Py Security в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-security
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/l-mb/python-refactoring-skills.git /tmp/python-refactoring-skills
mkdir -p .claude/skills
cp -r /tmp/python-refactoring-skills/skills/py-security .claude/skills/py-security
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Py Security в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Py Security, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Py Security не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Python Security Analysis and Remediation

Find and fix security vulnerabilities in Python code following Engineering Charter security principles.

Objectives

  1. Detect security vulnerabilities using automated scanners
  2. Identify SQL injection risks
  3. Find hardcoded secrets and credentials
  4. Detect weak cryptographic practices
  5. Fix vulnerabilities following secure coding patterns
  6. Prevent secrets from being committed to git

Required Tools

Add to [dependency-groups] dev: "bandit", "ruff"

  • bandit: AST-based security scanner
  • ruff --select S: Built-in Bandit rules (faster alternative)

Permissions: Run py-quality-setup first to configure .claude/settings.local.json with all needed tool permissions.

Discovery Phase

Run Security Scanners

bash
# Using bandit (comprehensive reports)
bandit -r . -f json -o bandit_report.json
bandit -r . -ll  # Show only medium/high severity

# Using ruff (faster, integrates with existing tooling)
ruff check . --select S
ruff check . --select S --output-format=json > security_report.json

Common Vulnerability Categories

High severity (fix immediately):

  • S608: SQL injection via string formatting
  • S105, S106, S107: Hardcoded passwords, secrets, keys
  • S501, S506: Weak SSL/TLS configuration
  • S324: Insecure hash functions (MD5, SHA1)
  • S602, S603, S604, S605, S606, S607: Shell injection risks

Medium severity:

  • S311: Insecure random number generation
  • S301, S302, S303: Insecure deserialization (pickle)
  • S701, S702: Jinja2 autoescape issues

Low severity (consider context):

  • S101: Use of assert (disabled in production)
  • S104: Binding to all interfaces (0.0.0.0)

Remediation Patterns

SQL Injection Prevention

python
# BEFORE - Vulnerable to SQL injection
def get_user(user_id: str) -> dict:
    cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
    return cursor.fetchone()

# AFTER - Use parametrized queries
def get_user(user_id: str) -> dict:
    cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
    return cursor.fetchone()

# For dynamic table/column names (cannot be parametrized)
from psycopg2 import sql

def get_data(table_name: str, column: str) -> list:
    # Validate inputs first!
    allowed_tables = {"users", "orders", "products"}
    if table_name not in allowed_tables:
        raise ValueError(f"Invalid table: {table_name}")

    query = sql.SQL("SELECT {column} FROM {table}").format(
        column=sql.Identifier(column),
        table=sql.Identifier(table_name)
    )
    cursor.execute(query)
    return cursor.fetchall()

Hardcoded Secrets Removal

python
# BEFORE - Hardcoded secrets (NEVER commit these)
API_KEY = "sk-1234567890abcdef"
DATABASE_URL = "postgres://user:password@localhost/db"
SECRET_TOKEN = "my-secret-token-123"

# AFTER - Use environment variables
import os

API_KEY = os.environ["API_KEY"]  # Raises if not set
DATABASE_URL = os.getenv("DATABASE_URL", "postgres://localhost/db")  # With default
SECRET_TOKEN = os.environ.get("SECRET_TOKEN")  # Returns None if not set

# For development, use python-dotenv
from dotenv import load_dotenv
load_dotenv()  # Loads from .env file (add .env to .gitignore!)
API_KEY = os.environ["API_KEY"]

Secure Random Number Generation

python
# BEFORE - Insecure for security-sensitive operations
import random

session_token = random.randint(100000, 999999)
api_key = ''.join(random.choices('abcdef0123456789', k=32))

# AFTER - Use secrets module for cryptographic randomness
import secrets

session_token = secrets.randbelow(900000) + 100000
api_key = secrets.token_hex(16)  # 32 hex characters
secure_password = secrets.token_urlsafe(32)  # URL-safe token

Secure Cryptography

python
# BEFORE - Weak hash functions
import hashlib

password_hash = hashlib.md5(password.encode()).hexdigest()  # Weak!
checksum = hashlib.sha1(data).hexdigest()  # Weak for security!

# AFTER - Use strong hash functions
import hashlib

# For passwords - use bcrypt or argon2
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)  # Verify

# For data integrity - use SHA256 or better
checksum = hashlib.sha256(data).hexdigest()
secure_hash = hashlib.blake2b(data).hexdigest()

Shell Command Injection Prevention

python
# BEFORE - Shell injection vulnerability
import os
import subprocess

filename = user_input
os.system(f"cat {filename}")  # Dangerous!
subprocess.call(f"ls {directory}", shell=True)  # Dangerous!

# AFTER - Use subprocess with list arguments (no shell)
import subprocess
from pathlib import Path

# Validate input first
filename = user_input
if not Path(filename).exists():
    raise ValueError("File not found")

# Use list form, no shell=True
subprocess.run(["cat", filename], check=True)
subprocess.run(["ls", directory], check=True)

# Even better - use Python libraries instead of shell commands
with open(filename) as f:
    content = f.read()

Git Hooks Integration

Add secret detection to git hooks (complement to py-git-hooks):

bash
# In .git/hooks/pre-commit, add before other checks:

# Detect potential secrets
if git diff --cached | grep -qiE '(password|secret|api[_-]?key|token|credentials)'; then
    echo "⚠️  Warning: Potential secrets detected in staged changes"
    echo "Review carefully before committing"
    read -p "Continue? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

Verification Checklist

  • ruff check . --select S reports no security issues
  • bandit -r . -ll reports no medium/high severity issues
  • No hardcoded secrets in codebase (grep for password, secret, api_key, token)
  • Secrets loaded from environment variables or .env file
  • .env file is in .gitignore
  • All SQL queries use parametrized queries
  • All tests pass after security fixes

Examples

Example: Security audit workflow

1. Scan: ruff check . --select S; bandit -r . -ll
2. Found: SQL injection (S608), hardcoded secret (S105)
3. Fix SQL: Use parametrized query with %s placeholders
4. Fix secret: Move to .env, use os.environ["API_KEY"]
5. Verify: Scans clean, tests pass

Related Skills

  • Prerequisites: py-quality-setup (configure ruff for security checks)
  • Enforcement: py-git-hooks (add security scanning to pre-commit)
  • See also: py-code-health (cleanup after security fixes)

Часто задаваемые вопросы

Что делает навык ИИ Py Security?

Security vulnerability detection and remediation for Python codebases. Identifies SQL injection, hardcoded secrets, weak cryptography, and other OWASP vulnerabilities.

Зачем использовать Py Security в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Py Security — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Py Security в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-security. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Py Security?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Py Security?

С любым количеством. В TypingMind вы можете использовать Py Security с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Py Security?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — l-mb. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип NousResearch

Antigravity Cli

NousResearch
ОрганизацияПопулярный

Работа с Antigravity CLI (agy): плагины, аутентификация, песочница.

53.5K
250.4K
Файлы: 1
Открыть
Логотип langgenius

Backend Code Review

langgenius
ОрганизацияПопулярный

Используйте только в том случае, если пользователь явно просит проверить или провести аудит серверного кода в `api/`. Поддерживаются проверки ожидающих изменений, отдельных файлов и вставленных diff. Не используйте этот навык для задач, ограниченных реализацией,…

24.9K
157.6K
Файлы: 4
Открыть
Логотип langgenius

Frontend Code Review

langgenius
ОрганизацияПопулярный

Используйте только в том случае, если пользователь явно просит проверить или провести аудит кода frontend в `web/` или `packages/dify-ui/`. Поддерживаются проверки ожидающих изменений, отдельных файлов и вставленных diff. Не используйте этот навык для…

24.9K
157.6K
Файлы: 8
Открыть
Логотип anthropics

Command Development

anthropics
ОрганизацияПопулярный

This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create…

23.8K
146.3K
Файлы: 9
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇