Skills Agentes

Secure Plugin Development

Úsalo al iniciar un plugin o tema de WordPress, al añadir hooks o funciones que manejan peticiones, opciones o salida; establece la línea base segura por defecto.

Oficial
Estrellas
57

en todo el repo

Actividad
55

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
5

últimos 90 días

Contexto
2k tok

106 tok en reposo

Paquete
4 archivos

21 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill secure-plugin-development --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Establece la línea base segura para plugins/temas: guarda ABSPATH, flujo de capacidad + nonce + sanitizado + escape, consultas preparadas
  • Actúa como skill router hacia el árbol de decisión de seguridad para elegir la ruta de entrada (navegador/API, renderer, cron o CLI)
  • Aplica valores por defecto seguros en opciones y fuerza prefijado único de funciones, hooks y opciones
  • Proporciona un esqueleto de plugin seguro con página admin protegida por capacidad y flujo completo verificar → autorizar → sanitizar → actuar → escapar

Úsalo cuando

  • Al crear el archivo principal de un plugin nuevo o añadir código a functions.php de un tema
  • Al registrar hooks (add_action/add_filter) que manejan entrada o renderizan salida
  • Al añadir páginas admin, ajustes, shortcodes, bloques, widgets o rutas REST
  • Al revisar un plugin existente para llevarlo a una línea base segura

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • “Crea el archivo principal de un nuevo plugin de WordPress”
    • “Añade una página de ajustes admin a mi plugin”
    • “Revisa este plugin existente y llévalo a una línea base segura”
    • “Registra un hook add_action que procese datos de un formulario”

    SKILL.md

    En inglés

    Secure plugin & theme development (baseline)

    When to use this skill

    Use this skill at the start of any WordPress development work and whenever you add a feature that crosses a trust boundary:

    • Creating a new plugin main file or theme functions.php addition.
    • Registering hooks (add_action / add_filter) that handle input or render output.
    • Adding admin pages, settings, shortcodes, blocks, widgets, or REST routes.
    • Reviewing an existing plugin to bring it up to a secure baseline.

    This is the router skill. Follow the security decision tree: choose the entry path (browser/API, renderer, cron, or CLI), then add the relevant data and policy branches. It explains when to combine focused skills and when browser nonce checks do not apply; do not load every skill for every task.

    Core principles (and why they matter)

    1. Never trust input; always escape output. Every value from $_GET, $_POST, $_REQUEST, $_COOKIE, the database, or a remote API is untrusted until sanitized, and untrusted again the moment it is echoed. These are two separate jobs.
    2. Block direct file access. Plugin files are reachable by URL. Without an ABSPATH guard, an attacker can execute them outside WordPress, bypassing all your checks.
    3. Separate authentication, CSRF, and authorization. Use a nonce for cookie-authenticated state changes and an appropriate capability/object check for privileged actions. REST API credentials, cron, and CLI have different trust models; follow the decision tree rather than adding browser checks everywhere.
    4. Use core APIs, not hand-rolled code. Prefer maintained sanitize/escape/DB/HTTP APIs, but choose the API and its arguments for the actual trust boundary.
    5. Least privilege by default. Default options to the safe value, scope capabilities tightly, and expose the minimum surface.
    6. Fail closed. On any failed check, stop and return an error — never fall through.

    Step-by-step implementation

    1. Guard the file: defined( 'ABSPATH' ) || exit; at the top of every PHP file.
    2. Namespace everything: prefix functions, hooks, options, and globals (e.g. my_plugin_*) to avoid collisions and accidental overrides.
    3. Choose the handler trust model using the decision tree:
      1. Apply transport-appropriate authentication and CSRF protection.
      2. Check authority over the action and specific resource.
      3. Validate input shape/type, unslash WordPress-slashed request input, and sanitize.
      4. Use $wpdb->prepare() for dynamic values in custom queries.
      5. Escape at each output sink for its actual context.
    4. Set safe defaults for all options; validate on save and on read.
    5. Enqueue assets properly (wp_enqueue_script/style) and pass data via wp_localize_script() rather than inline-echoing PHP into JS.
    6. Keep secrets out of the repo and out of client-readable output.

    Supporting references

    Reference Load when
    Secure plugin baseline checklist Before final verification of the secure plugin baseline controls.
    Choose the security review path Selecting focused skills for the entry point and all relevant data and risk branches.
    Secure plugin skeleton Implementing a capability-gated plugin admin page and the full settings-save flow.

    Common AI mistakes / anti-patterns

    Mistake 1 — No ABSPATH guard

    // ❌ Insecure: file executes if requested directly over HTTP.
    <?php
    function my_plugin_init() { /* ... */ }
    
    // ✅ Secure: bail unless loaded within WordPress.
    <?php
    defined( 'ABSPATH' ) || exit;
    
    function my_plugin_init() { /* ... */ }
    

    Mistake 2 — Doing the work before the security checks

    // ❌ Insecure: option saved before anything is verified.
    function my_plugin_save() {
        update_option( 'my_opt', $_POST['val'] );
        check_admin_referer( 'my_plugin_save' );
        current_user_can( 'manage_options' );
    }
    
    // ✅ Secure: verify, authorize, sanitize, THEN act.
    function my_plugin_save() {
        check_admin_referer( 'my_plugin_save', 'my_plugin_nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Forbidden', 'my-plugin' ), 403 );
        }
        $val = isset( $_POST['val'] ) ? sanitize_text_field( wp_unslash( $_POST['val'] ) ) : '';
        update_option( 'my_opt', $val );
    }
    

    Mistake 3 — Rolling your own instead of using core APIs

    // ❌ Insecure: manual SQL, manual escaping, raw remote fetch.
    $rows = $wpdb->get_results( "SELECT * FROM t WHERE id = " . $_GET['id'] );
    echo "<a href=" . $_GET['url'] . ">x</a>";
    $body = file_get_contents( $remote_url );
    
    // ✅ Secure: prepared query, escaped output, HTTP API.
    $id   = absint( $_GET['id'] ?? 0 );
    $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}t WHERE id = %d", $id ) );
    echo '<a href="' . esc_url( wp_unslash( $_GET['url'] ?? '' ) ) . '">x</a>';
    $response = wp_remote_get( $remote_url );
    $body     = is_wp_error( $response ) ? '' : wp_remote_retrieve_body( $response );
    

    Mistake 4 — Unsafe defaults

    // ❌ Insecure: feature ships enabled, capability defaults wide open.
    add_option( 'my_plugin_allow_uploads', true );
    
    // ✅ Secure: default to the safe value; opt-in to risk.
    add_option( 'my_plugin_allow_uploads', false );
    

    Correct code examples

    A minimal but complete secure plugin skeleton — ABSPATH guard, an admin page behind a capability, and the full verify → authorize → sanitize → act → escape flow — lives in references/secure-plugin-skeleton.php.

    Checklist

    • Every PHP file opens with defined( 'ABSPATH' ) || exit;.
    • Functions, hooks, and options are uniquely prefixed.
    • Each request handler verifies nonce, then capability, then sanitizes input.
    • All custom DB access uses $wpdb->prepare().
    • All dynamic output is escaped at the point of echo.
    • Options have safe defaults and are validated on save.
    • Remote requests use the WP HTTP API (wp_remote_*), not file_get_contents/cURL.
    • No secrets, keys, or credentials are hard-coded or sent to the browser.
    • Scripts are enqueued and given data via wp_localize_script().

    Official references

    Reproducido de wpultimatesecurity/WordPress-Security-Skills bajo licencia MIT. Leer esta página en markdown.

    Archivos

    4 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Los ejemplos usan PHP 7.4; comprueba cada API contra las versiones objetivo de WordPress/PHP y usa versiones mantenidas en producción.

    Detalles

    Categoría
    Seguridad
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wpultimatesecurity/WordPress-Security-Skills

    Este repo incluye 27 skills. Si instalas uno, normalmente ya tienes los demás. Ver el pack WordPress-Security-Skills entero y su comando de instalación

    Úsalo al auditar o revisar código de un plugin o tema WordPress existente, triar un informe de vulnerabilidad o endurecer código heredado, con una metodología sistemática.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando un plugin o tema empaquete una librería de terceros, cargue un asset desde un CDN, ejecute código remoto, use Composer o prepare el zip distribuible.

    Costo de contexto al activarse
    4.5k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al construir bloques dinámicos o funciones del editor de bloques: render_callback, ServerSideRender, datos REST o register_rest_field, para evitar XSS almacenado y control de acceso roto.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al escribir código para WordPress multisite: switch_to_blog, páginas de red, get_sites o capacidades que difieren entre sitio y red. Evita fugas de datos entre sitios y escaladas de privilegios de red.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al mostrar o imprimir cualquier valor dinámico en PHP o plantillas de WordPress, escapando en el punto de salida con esc_html, esc_attr, esc_url, esc_js, esc_textarea o wp_kses_post para prevenir XSS.

    Costo de contexto al activarse
    2.4k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Skills relacionados

    Úsalo al construir o revisar funciones de plugin o tema de WordPress que llaman a un LLM: chatbots, generación de contenido, RAG, agentes con herramientas, Abilities API o exposición MCP.

    Costo de contexto al activarse
    3.6k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al registrar o manejar AJAX en WordPress vía admin-ajax.php: verifica el nonce, comprueba permisos, sanitiza cada campo y responde con wp_send_json_*, evitando CSRF e inyecciones.

    Costo de contexto al activarse
    3.1k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad