Skills Agentes

Output Escaping

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

Oficial
Estrellas
57

en todo el repo

Actividad
54

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
4

últimos 90 días

Contexto
2.4k tok

102 tok en reposo

Paquete
3 archivos

13 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill output-escaping --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Escapa cada valor dinámico en el punto de salida usando esc_html, esc_attr, esc_url, esc_js, esc_textarea o wp_kses_post según el contexto
  • Aplica las variantes i18n (esc_html__, esc_attr_e) a cadenas traducidas antes de imprimirlas
  • Valida y sanea URLs de redirección con esc_url_raw, wp_validate_redirect y wp_safe_redirect
  • Revisa el código JavaScript para evitar sinks DOM peligrosos como innerHTML o .html()

Úsalo cuando

  • Al hacer echo o print de cualquier variable dentro de HTML, atributos, URLs, JS inline o textareas
  • Al renderizar contenido en plantillas, shortcodes, bloques, widgets o respuestas REST que devuelven HTML
  • Al pasar datos a wp_localize_script o insertarlos mediante JavaScript en el DOM
  • Al construir un redirect con un valor de $_GET u otro origen externo

No lo uses cuando

    Qué lo activa

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

    • “Revisa si estoy escapando bien esta variable antes de hacer echo en mi plantilla”
    • “¿Qué función de escaping debo usar para este atributo href?”
    • “Comprueba si mi código es vulnerable a XSS almacenado”
    • “Ayúdame a corregir este wp_redirect inseguro”

    SKILL.md

    En inglés

    Output escaping (XSS prevention)

    When to use this skill

    Use this skill whenever a dynamic value is sent to the browser:

    • echo / print of any variable into HTML.
    • Values placed into HTML attributes (value, href, src, class, data-*).
    • URLs in href / src / redirects.
    • Data injected into inline <script> or JS via wp_localize_script.
    • Content rendered in templates, shortcodes, blocks, widgets, REST responses that return HTML.

    Escape as late as possible, at the point of output, choosing the function that matches the context the value lands in. This is separate from input sanitization — do both.

    Core principles (and why they matter)

    1. Escape on output, every time. XSS happens when untrusted data is interpreted as markup or script. Escaping at output neutralizes it regardless of how it got stored.
    2. Escape even "trusted" data. Database values, option values, and your own earlier output can still contain markup. Escape at render anyway — it's cheap and consistent.
    3. Context determines the function. HTML body → esc_html; attribute → esc_attr; URL → esc_url; inline JS → esc_js (or wp_json_encode); rich HTML → wp_kses_post. Using the wrong one (e.g. esc_html inside an attribute) can still be exploitable.
    4. Escape the whole value, late. Don't concatenate escaped + unescaped fragments; escape the final value as it is echoed.
    5. Translations are output too. Use esc_html__(), esc_attr_e(), etc. — never echo a raw __() result into a sensitive context.
    6. wp_kses_post() is for intentional HTML. When a value must contain markup, allow a safe subset rather than escaping it all away.

    Step-by-step implementation

    1. Identify the context at the echo site (HTML text, attribute, URL, JS, textarea).
    2. Pick the matching escaping function.
    3. Wrap the value at the moment of output.
    4. For translatable strings, use the esc_*__ / esc_*_e variant.
    5. For values that legitimately contain HTML, use wp_kses_post() / wp_kses().

    Supporting references

    Reference Load when
    Output escaping checklist Before final verification of the output escaping controls.
    Output escaping cheatsheet Choosing the applicable WordPress API or control for context-specific output escaping.

    Common AI mistakes / anti-patterns

    Mistake 1 — Echoing a value with no escaping

    // ❌ Insecure: stored XSS if $name ever contains markup.
    echo '<h2>' . $name . '</h2>';
    
    // ✅ Secure: escape for HTML context.
    echo '<h2>' . esc_html( $name ) . '</h2>';
    

    Mistake 2 — Wrong context (HTML escaper inside an attribute)

    // ❌ Insecure: esc_html doesn't encode quotes the way attributes need.
    echo '<input value="' . esc_html( $value ) . '">';
    
    // ✅ Secure: esc_attr for attribute context.
    echo '<input value="' . esc_attr( $value ) . '">';
    

    Mistake 3 — Unescaped URLs (allows javascript: and injection)

    // ❌ Insecure: attacker controls the scheme/markup.
    echo '<a href="' . $url . '">link</a>';
    
    // ✅ Secure: esc_url strips dangerous schemes and encodes the URL.
    echo '<a href="' . esc_url( $url ) . '">link</a>';
    

    Mistake 4 — Injecting PHP into inline JS without esc_js/JSON

    // ❌ Insecure: breaks out of the string and into script.
    echo '<script>var label = "' . $label . '";</script>';
    
    // ✅ Secure: esc_js for a single quoted string...
    echo '<script>var label = "' . esc_js( $label ) . '";</script>';
    // ...or, better, pass structured data as JSON:
    echo '<script>var data = ' . wp_json_encode( $data ) . ';</script>';
    

    Mistake 5 — Using wp_kses_post() where escaping is required (and vice versa)

    // ❌ Wrong tool: kses lets markup through where you wanted plain text.
    echo '<td>' . wp_kses_post( $plain_title ) . '</td>';
    
    // ✅ Plain text → esc_html; intentional rich HTML → wp_kses_post.
    echo '<td>' . esc_html( $plain_title ) . '</td>';
    echo '<div class="bio">' . wp_kses_post( $rich_bio ) . '</div>';
    

    Mistake 6 — Translated strings echoed unescaped

    // ❌ Insecure: translation files can contain markup; raw echo into a tag.
    echo '<p>' . __( 'Welcome, %s', 'my-plugin' ) . '</p>';
    
    // ✅ Secure: escape the translated output.
    printf( '<p>%s</p>', esc_html__( 'Welcome back', 'my-plugin' ) );
    

    Mistake 7 — Redirect target not validated

    // ❌ Insecure: open redirect to an attacker-controlled site.
    $redirect = $_GET['redirect_to'];
    wp_redirect( $redirect );
    exit;
    
    // ✅ Secure: the "escape" for a Location target is validation + wp_safe_redirect.
    $redirect = isset( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : '';
    $redirect = wp_validate_redirect( $redirect, admin_url() );
    wp_safe_redirect( $redirect );
    exit;
    

    Mistake 8 — Using wp_kses_post where a tighter allowlist is needed

    // ❌ Risky: wp_kses_post allows many tags you may not want in a caption.
    echo wp_kses_post( $caption );
    
    // ✅ Secure: define a custom allowlist when the context is narrower.
    $allowed = array(
        'a'      => array( 'href' => array() ),
        'em'     => array(),
        'strong' => array(),
    );
    echo wp_kses( $caption, $allowed );
    

    Related: see the input-sanitization-validation skill for validating redirect URLs on input and the filesystem-security skill for path escaping.

    Mistake 9 — Escaping in PHP, then re-injecting in JavaScript

    // ❌ Insecure: PHP passed the value safely through wp_localize_script or
    // wp_json_encode, but the script decodes it into markup.
    const name = myPluginData.displayName;
    document.querySelector( '#greeting' ).innerHTML = 'Hello ' + name;
    jQuery( '#title' ).html( myPluginData.title );
    
    // ✅ Secure: insert untrusted values as text in the DOM.
    document.querySelector( '#greeting' ).textContent = 'Hello ' + myPluginData.displayName;
    jQuery( '#title' ).text( myPluginData.title );
    

    Server-side escaping protects the transfer into the page, not what client code does next. Review DOM sinks (innerHTML, outerHTML, insertAdjacentHTML, document.write, jQuery .html()/.append() with strings, location assignments) in plugin scripts.

    Correct code examples

    A complete context → function reference (with esc_url vs esc_url_raw, the i18n variants, and wp_kses allowlist usage) is in references/escaping-cheatsheet.md.

    // A small template snippet that escapes every dynamic value in context.
    ?>
    <article id="post-<?php echo esc_attr( $post_id ); ?>" class="<?php echo esc_attr( $css ); ?>">
        <h2><a href="<?php echo esc_url( $permalink ); ?>"><?php echo esc_html( $title ); ?></a></h2>
        <div class="content"><?php echo wp_kses_post( $content ); ?></div>
        <a class="more" href="<?php echo esc_url( $permalink ); ?>">
            <?php echo esc_html__( 'Read more', 'my-plugin' ); ?>
        </a>
    </article>
    <?php
    

    Checklist

    • Every echoed variable is escaped at the point of output.
    • HTML text uses esc_html / esc_html__ / esc_html_e.
    • Attribute values use esc_attr / esc_attr__ / esc_attr_e.
    • URLs in markup use esc_url (esc_url_raw only for storage/redirects).
    • Inline JS uses esc_js or, preferably, wp_json_encode.
    • Textarea contents use esc_textarea.
    • Intentional HTML uses wp_kses_post / wp_kses with an allowlist.
    • Translatable strings use the esc_* i18n variants.
    • No escaped/unescaped string concatenation that defeats escaping.
    • Client-side code inserts localized or fetched values with textContent / .text(), not innerHTML / .html(); URLs assigned to location or href are validated.

    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