记忆

Python Hardener

试用

Hardens Python scripts by applying a complete security review, clean-code refactoring, robust error handling, proper logging, and full docstring coverage — t...

它能做什么

You are taking one or more Python scripts and producing corrected, hardened versions of those same files — plus a Markdown documentation file — without inventing new filenames or a migration project around them.

技能文档

Python Hardener

You are taking one or more Python scripts and producing corrected, hardened versions of those same files — plus a Markdown documentation file — without inventing new filenames or a migration project around them.

What to deliver

  1. The same Python files, corrected in place. Keep original filenames exactly.
  2. One Markdown documentation file named .md covering both the security measures applied and how each module works.

Do not create .env.example, migration guides, requirements.txt, or any file not listed above unless the user explicitly asks for it.


Analysis pass — what to look for

Read the entire file before making any changes. Build a mental list of issues across four categories:

Security

  • SQL/NoSQL injection — table names, column names, or user input interpolated directly into query strings via f-strings or % formatting. Fix with allowlist validation (assert table in frozenset({...})); parameterised queries for values.
  • Shell injection — any subprocess call that uses shell=True or joins a command into a single string. Fix with list-form calls and no shell=True.
  • Path traversal — file paths constructed from user input without Path.resolve() and an allowlist check.
  • CWD mutation — os.chdir() permanently changes process working directory. Replace with subprocess.run(["git", "-C", repo_path, ...]) or equivalent.
  • Secrets in code — API keys, passwords hardcoded. Flag for env-var migration.

Error handling

  • Bare except: — swallows every exception including KeyboardInterrupt, SystemExit, and MemoryError. Replace with specific types: json.JSONDecodeError, subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError, ValueError, etc. Always log the caught exception.
  • Silent pass in exception blocks — hides failures. Add at minimum a logger.warning(...) or logger.error(...) with the exception detail.
  • Missing finally / context managers — database connections, file handles, or network sockets that are never closed. Use with statements or contextmanager.

Performance / resource management

  • File opened on every call — e.g. a log() function that opens the log file each time it runs. Configure handlers once (e.g. RotatingFileHandler) and reuse.
  • DB connection leaks — connect() called in every method, connection never closed. Wrap in a @contextmanager that calls conn.close() in finally.
  • Module-level side effects — Path.mkdir(), sqlite3.connect(), or network calls at import time. Move into main() or __init__().
  • Non-atomic writes — writing state/config files directly risks a torn write if the process is interrupted. Use tempfile.mkstemp() then os.replace().

Clean code

  • Rename single-letter or cryptic variables to descriptive names.
  • Break functions that do more than one thing.
  • Add type hints to function signatures.

Rewrite rules

Apply every fix from the analysis pass. Additionally:

Logging — Replace print() statements used for operational output and any hand-rolled file-append logging with Python's logging module:

  • Configure once via a setup function (not at module level, not per-call).
  • Use RotatingFileHandler (10 MB / 7 backups) for file output and a StreamHandler for console.
  • Read log level from an environment variable, falling back to INFO.
  • Log errors with logger.error("...", exc_info=True) or include the exception string explicitly so the cause is always visible.

Docstrings — Add Google-style docstrings to every public function, method, and class:

def export_csv(self, table: str) -> Optional[Path]:
    """
    Exports a table as a CSV file.

    Args:
        table: Table name — must be in {'documents', 'skills', 'symlinks'}.

    Returns:
        Path to the generated CSV file, or None if the table is empty.

    Raises:
        ValueError: If the table name is not in the allowlist.
        sqlite3.Error: On database errors.
        OSError: On write errors.
    """

Language-specific stubs — If the code generates skeleton files for multiple programming languages, make sure each language gets its own idiomatic entry point (not Python def main(): / if __name__ == "__main__": for Perl, Tcl, Shell, etc).


Documentation file

Write a single Markdown file (.md) with these sections:

  1. Overview — one-paragraph summary of what the script(s) do.
  2. Architecture — ASCII diagram or table showing the main components and their relationships.
  3. Configuration — environment variables consumed, with defaults.
  4. API / Functions — per-module table of public functions (name, signature, what it does).
  5. Security — table of threats addressed and the countermeasure applied.
  6. Error handling — table mapping each function to the exceptions it handles and what happens on failure.

Style constraints

  • Preserve the original author's overall structure and naming conventions unless they are actively harmful (e.g., a function named x that does a critical thing).
  • Do not add versioning, changelogs, or migration notes unless asked.
  • Do not invent new filenames beyond the one documentation .md.
  • If the user's .env already exists and is mentioned as the source of truth, do not create .env.example.

Checklist before delivering

  • Every bare except: replaced with specific exception type(s) + logging
  • No os.chdir() — use subprocess ... -C or cwd= argument instead
  • SQL/shell injection vectors closed
  • Connections / file handles closed via context manager
  • Logging configured once, not per-call
  • Atomic writes (tempfile + os.replace()) for state/config files
  • All public functions have docstrings with Args/Returns/Raises
  • Type hints on function signatures
  • Module-level side effects moved into main() or __init__()
  • Documentation .md file present and accurate

相关技能

在本地磁盘以分类纯 Markdown 文件保存需要长期留存的事实,与智能体内置记忆并存。

作者 Iván559 次安装18 星标

把自然语言描述转为结构化 JSON,并由 mcp-diagram-generator MCP 服务生成 Draw.io、Mermaid 或 Excalidraw 图表文件。

作者 nssa.io1.0k 次安装47 星标

以 AI 机器人身份加入视频会议,提供语音、虚拟形象与屏幕共享四种模式。

作者 johnpatternai22 次安装8 星标

诊断生产力系统反复失效的根因,给出最小干预——容量测算、瓶颈定位、可靠的本地记录。

作者 Iván855 次安装69 星标

执行 Git 操作(提交、分支、合并、变基、冲突解决与恢复)时强制套用安全规则。

作者 Iván535 次安装31 星标

kikikari 的更多技能

浏览全部技能

Robust JSON parsing and validation with Pydantic schemas, JSON Schema validation, batch processing, and automatic JSON repair for LLM outputs. Use when Codex...

作者 kikikari15 次安装

Permanent log collection agent. Collects logs and history from all nodes via SSH/VPN every 3 hours. Stores in logs.db with 30-day retention. Multi-node capab...

作者 kikikari14 次安装

Musikerkennung und AudD-Kontoverwaltung über den offiziellen AudD-MCP-Server (https://mcp.audd.io) und/oder die direkte HTTP-API. Ein eigener api_token ist optional — funktioniert per OAuth-MCP ganz ohne Token, mit Trial-Plan und mit bezahltem Plan, ebenso mit dauerhaft hinterlegtem Token. Nutze diesen Skill bei Songerkennung — "welcher Song ist das?", Audio-Clip oder Datei identifizieren, Shazam-artig, Radio-/Twitch-/YouTube-Streams überwachen, DJ-Sets, Podcasts oder Videos nach Tracks durchsuchen, Tracklists, Airplay-Monitoring, Copyright-Check — und bei allem rund um das AudD-Konto: api_token eintragen, hinterlegen, aus der Zwischenablage in den Secret-Vault übernehmen, in .env setzen, rotieren; Request-Kontingent, Verbrauch, Trial-Restlaufzeit, Plan-Upgrade, Rechnungen. Auch anwenden, wenn AudD nicht namentlich genannt wird, aber ein Audio-/Video-Link oder eine lokale Audiodatei identifiziert werden soll.

作者 kikikari

Baut einen "Companion" — eine lokal laufende Beobachtungs-Anwendung: kleiner Server auf 127.0.0.1, Doppelklick-Starter, installierbare PWA, optionale Browser-Erweiterung, Meldung beim Zustandswechsel, Dauerbetrieb im Container. Nutze diesen Skill, sobald jemand etwas dauerhaft im Auge behalten und benachrichtigt werden will — Livestreams, Kanäle, Feeds, Preise, Build-Zustände, Serververfügbarkeit, Ordner, Warteschlangen. Auch wenn die Anfrage nur nach einem Teil klingt: "sag mir Bescheid wenn X online geht", "kleines Tool das im Hintergrund läuft", "Statusseite für Y", "als App installierbar", "soll dauerhaft laufen", "auch nach Neustart", "als Docker-Container". Besonders wichtig bei einer einzelnen HTML-Datei, die fremde Daten abruft: ob das trägt, hängt an einer CORS-Freigabe, die man vorher prüfen muss — sonst bleibt die Datei beim Nutzer leer.

作者 kikikari

Diagnose und Einrichtung fremder, offizieller MCP-Server (Konnektoren) in der Claude-App. Nutze diesen Skill, wenn jemand fragt: gibt es für diesen Anbieter einen offiziellen MCP-Server, trag mir den als Konnektor ein, warum sehe ich die Tools von dem Dienst nicht, welche Scopes braucht er, mein Konnektor antwortet nicht, MCP-Server hinzufügen, Connector verbinden, Server hängt in "connecting", invalid_scope, 401 nach Wochen, Tools verschwunden. Unterscheidet fünf Zustände — offen ohne Konto, verbunden mit Tools, verbunden ohne Tools, installiert aber unangemeldet, gar nicht vorhanden — und nennt pro Zustand den konkreten nächsten Schritt. Nicht anwenden bei reinen Preisfragen zu einer API, bei Code-Anfragen oder bei der allgemeinen Frage, was MCP überhaupt ist.

作者 kikikari

Führt Architekturanalyse, Komplexitätsmessung, Abstraktionsschicht-Design, Vendor Lock-in Bewertung, Refactoring-Planung und Software-Qualitätsbewertung durch.

作者 kikikari