Skills Agentes

Shortcode Block Security

Úsalo al registrar un shortcode con add_shortcode o un bloque dinámico con render_callback. Normaliza y valida atributos y escapa toda la salida para evitar XSS almacenado y reflejado.

Oficial
Estrellas
57

en todo el repo

Actividad
50

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
3

últimos 90 días

Contexto
2.1k tok

91 tok en reposo

Paquete
3 archivos

12 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill shortcode-block-security --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Normaliza atributos de shortcodes y bloques con shortcode_atts() y los sanitiza al tipo esperado
  • Escapa toda la salida renderizada según su contexto con esc_html, esc_attr, esc_url o wp_kses_post
  • Evita ejecutar do_shortcode() sobre contenido no confiable
  • Hace que los callbacks de renderizado devuelvan cadenas en lugar de usar echo

Úsalo cuando

  • Al registrar un shortcode con add_shortcode()
  • Al leer o mostrar atributos de shortcode ($atts) o contenido encerrado ($content)
  • Al registrar un bloque dinámico con un render_callback
  • Al construir HTML, URLs o clases a partir de entradas de shortcode o bloque

No lo uses cuando

    Qué lo activa

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

    • “Registra un shortcode [my_card] que muestre un título y un enlace”
    • “Crea el render_callback de un bloque dinámico de Gutenberg con atributos bgColor y heading”
    • “Revisa este shortcode por posibles fallos de XSS almacenado”

    SKILL.md

    En inglés

    Shortcode & dynamic block security

    When to use this skill

    Use this skill whenever code renders content from shortcodes or dynamic blocks:

    • Registering a shortcode with add_shortcode().
    • Reading or outputting shortcode attributes ($atts) or enclosed content ($content).
    • Registering a dynamic block with a render_callback.
    • Reading block attributes in a server-side render.
    • Building HTML, URLs, or classes from shortcode/block input.

    Shortcodes and dynamic blocks are stored XSS sinks: a contributor enters [my_card title="<script>..."] and the render callback echoes it unescaped. Every attribute must be sanitized and every output escaped.

    Related: see the output-escaping skill for context-correct escaping and the gutenberg-block-editor-security skill for broader block-editor surfaces.

    Core principles (and why they matter)

    1. shortcode_atts() sets defaults; it does NOT sanitize. The returned array still holds raw user input. Sanitize each value before use.
    2. Block attributes are user input too. Declaring type: 'string' in block.json does not escape HTML or JavaScript for you; sanitize on render.
    3. Escape at render for the exact context. HTML body → esc_html(). HTML attribute → esc_attr(). URL → esc_url(). Rich HTML → wp_kses_post() with an allowlist.
    4. Do not store unescaped attribute values. If you persist them, sanitize on save and escape on read.
    5. Never pass shortcode/block input to do_shortcode() or eval() uncontrolled. Both can execute arbitrary shortcodes or code.
    6. Return, don't echo. Shortcode and block render callbacks must return strings; echoing produces unexpected output placement.

    Step-by-step implementation

    1. In the shortcode callback, call shortcode_atts() with a complete default map.
    2. Sanitize each attribute to its expected type (absint, sanitize_text_field, esc_url_raw, sanitize_key).
    3. In a block render_callback, read attributes from the $attributes array and sanitize them the same way.
    4. Build the markup by concatenating escaped values.
    5. Return the complete markup string.
    6. For rich content, use wp_kses_post() or a tightly scoped wp_kses() allowlist.

    Supporting references

    Reference Load when
    Shortcode & dynamic block security checklist Before final verification of the shortcode & dynamic block security controls.
    Secure shortcode and dynamic block Implementing shortcode and dynamic-block render callbacks with validated attributes and escaped markup.

    Common AI mistakes / anti-patterns

    Mistake 1 — Echoing $atts directly

    // ❌ Insecure: stored XSS through the title attribute.
    function my_plugin_card_shortcode( $atts ) {
        return '<div class="card"><h3>' . $atts['title'] . '</h3></div>';
    }
    
    // ✅ Secure: default, then sanitize, then escape.
    function my_plugin_card_shortcode( $atts ) {
        $atts = shortcode_atts(
            array(
                'title' => '',
                'link'  => '',
            ),
            $atts,
            'my_plugin_card'
        );
    
        $title = sanitize_text_field( $atts['title'] );
        $link  = esc_url_raw( $atts['link'] );
    
        $output = '<div class="card">';
        if ( $link ) {
            $output .= '<h3><a href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a></h3>';
        } else {
            $output .= '<h3>' . esc_html( $title ) . '</h3>';
        }
        $output .= '</div>';
    
        return $output;
    }
    

    Mistake 2 — Trusting shortcode_atts() to sanitize

    // ❌ Insecure: shortcode_atts only supplies defaults and filters unknown keys.
    $atts = shortcode_atts( array( 'class' => '' ), $atts );
    echo '<div class="' . $atts['class'] . '">...</div>';
    
    // ✅ Secure: sanitize the value after normalizing it.
    $atts  = shortcode_atts( array( 'class' => '' ), $atts, 'my_plugin_box' );
    $class = sanitize_html_class( $atts['class'] );
    echo '<div class="' . esc_attr( $class ) . '">...</div>';
    

    Mistake 3 — Dynamic block render callback echoing attributes

    // ❌ Insecure: block attributes echoed raw.
    function my_plugin_render_banner( $attributes ) {
        ?>
        <div class="banner" style="background: <?php echo $attributes['bgColor']; ?>">
            <?php echo $attributes['heading']; ?>
        </div>
        <?php
    }
    
    // ✅ Secure: sanitize attributes and escape for the output context.
    function my_plugin_render_banner( $attributes ) {
        $bg_color = isset( $attributes['bgColor'] ) ? sanitize_hex_color( $attributes['bgColor'] ) : '#ffffff';
        $heading  = isset( $attributes['heading'] ) ? sanitize_text_field( $attributes['heading'] ) : '';
    
        return sprintf(
            '<div class="banner" style="background: %s"><h2>%s</h2></div>',
            esc_attr( $bg_color ),
            esc_html( $heading )
        );
    }
    

    Mistake 4 — Allowing arbitrary HTML through attributes

    // ❌ Insecure: an attacker can inject script/event handlers.
    function my_plugin_render_note( $attributes ) {
        return '<div>' . $attributes['content'] . '</div>';
    }
    
    // ✅ Secure: constrain rich markup with wp_kses_post.
    function my_plugin_render_note( $attributes ) {
        $content = isset( $attributes['content'] ) ? $attributes['content'] : '';
        return '<div>' . wp_kses_post( $content ) . '</div>';
    }
    

    Mistake 5 — Running do_shortcode() on untrusted input

    // ❌ Insecure: executes arbitrary shortcodes supplied by a visitor.
    echo do_shortcode( $_POST['content'] );
    
    // ✅ Secure: do not run do_shortcode on user input; if required, sanitize first.
    $content = wp_kses_post( wp_unslash( $_POST['content'] ?? '' ) );
    

    Correct code examples

    A complete secure shortcode and dynamic-block render callback is in references/secure-shortcode-block.php.

    Checklist

    • shortcode_atts() provides defaults for every supported attribute.
    • Each shortcode attribute is sanitized to its expected type after normalization.
    • Block attributes are sanitized inside render_callback, not trusted from block.json types.
    • All rendered output is escaped for its context (esc_html, esc_attr, esc_url, wp_kses_post).
    • CSS classes use sanitize_html_class() (or esc_attr() with an allowlist).
    • Colors use sanitize_hex_color() where appropriate.
    • The callback returns a string; it does not echo directly.
    • do_shortcode() is never run on untrusted input.

    Official references

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

    Archivos

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

    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 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.

    Costo de contexto al activarse
    2k 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

    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