# Gutenberg Block Editor Security
> Ú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.
Fuente: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/gutenberg-block-editor-security
Markdown: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/gutenberg-block-editor-security.md
Repositorio: https://github.com/wpultimatesecurity/WordPress-Security-Skills
Autor: wpultimatesecurity
Licencia: MIT
Actualizado: hace 2 meses
Coste de contexto: 105 tok instalada, 2.6k tok al activarse, 3.6k tok con todos los archivos del bundle
Bundle: 3 archivos, 14 KB
Permisos que pide: ninguno declarado
## Instalación
Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina.
```bash
# Claude Code
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent claude-code
# Cursor
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent cursor
# Codex
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent codex
# Gemini CLI
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent gemini
# Windsurf
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent windsurf
# Cline
npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill gutenberg-block-editor-security --agent cline
```
## Qué hace
- Sanitiza y escapa los atributos de bloques y la salida de render_callback según el contexto
- Añade permission_callback reales a los campos REST del editor con register_rest_field
- Sanitiza contenido de RichText con wp_kses_post en vez de almacenarlo en crudo
- Valida el origen y la forma de los mensajes postMessage y evita sinks como RawHTML o innerHTML
## Cuándo usarla
- Construyes bloques dinámicos con un render_callback en PHP
- Usas ServerSideRender para obtener markup renderizado en el servidor dentro del editor
- Expones o guardas datos de bloques mediante register_rest_field()
- Trabajas con RichText o permites markup en los atributos de un bloque
## Cuándo no
- Trabajas con bloques estáticos simples que no interactúan con el editor más allá de eso
## Qué la activa
- "Revisa la seguridad de este render_callback de un bloque dinámico"
- "Añade permission_callback a este register_rest_field del editor"
- "Sanitiza este contenido de RichText antes de guardarlo"
- "Comprueba si este ServerSideRender expone datos sin control de permisos"
## Archivos
- SKILL.md — 10 KB
- references/checklist.md — 815 B
- references/secure-block-editor.php — 3 KB
## SKILL.md
Reproducido tal cual desde wpultimatesecurity/WordPress-Security-Skills bajo MIT. Esta sección es el documento original y está en inglés.
# Gutenberg block editor security
## When to use this skill
Use this skill whenever code interacts with the block editor beyond simple static blocks:
- Building dynamic blocks with a PHP `render_callback`.
- Using `ServerSideRender` to fetch server-rendered markup in the editor.
- Exposing or saving block data via `register_rest_field()`.
- Handling `RichText` content or allowing markup in block attributes.
- Enqueuing block-editor assets that call custom REST endpoints.
The block editor trusts server-rendered HTML and REST field values. If the server
returns unescaped data or allows unauthorized writes, the vulnerability lands inside
the editor UI and the saved post content.
Related: see the `shortcode-block-security` skill for attribute sanitization basics
and the `rest-api-security` skill for REST endpoints.
## Core principles (and why they matter)
1. **Block attributes are user input.** Declaring a type in `block.json` validates shape
but does not sanitize HTML or JavaScript. Sanitize in `render_callback`.
2. **Server render output must be escaped.** The editor and front-end both render the
callback's return value; escape for the context (HTML, attribute, URL, rich text).
3. **Editor REST fields need real permission callbacks.** `register_rest_field()` `update_callback`
must check `current_user_can( 'edit_post', $post_id )` or a matching capability.
4. **RichText allows markup — constrain it.** Use `wp_kses_post()` or a custom allowlist
instead of raw storage.
5. **`ServerSideRender` requests are REST requests.** They are public unless the block's
REST route or render callback enforces capability checks.
6. **Use `apiFetch` with the `X-WP-Nonce` header.** Modern editor JS uses `apiFetch`, which
adds the nonce automatically for same-site REST requests.
## Step-by-step implementation
1. Define block attributes in `block.json` with types and defaults.
2. In the PHP `render_callback`, sanitize each attribute before use.
3. Build markup with escaped values (`esc_html`, `esc_attr`, `esc_url`, `wp_kses_post`).
4. If the block needs server-side rendering in the editor, ensure the underlying data source
enforces permissions.
5. For `register_rest_field()` used by the block:
- Add `schema` with `arg_options` sanitize/validate callbacks.
- In `update_callback`, check the acting user's capability on the object.
6. For `RichText`, sanitize on save with `wp_kses_post()` and escape on render.
### Supporting references
| Reference | Load when |
| --- | --- |
| [Gutenberg block editor security checklist](references/checklist.md) | Before final verification of the gutenberg block editor security controls. |
| [Secure block editor integration](references/secure-block-editor.php) | Implementing a dynamic block render callback and capability-gated REST field updates. |
## Common AI mistakes / anti-patterns
### Mistake 1 — Render callback echoing attributes unescaped
```php
// ❌ Insecure: stored XSS through a block attribute.
function my_plugin_render_alert( $attributes ) {
return '
' . $attributes['message'] . '
';
}
```
```php
// ✅ Secure: sanitize and escape the attribute.
function my_plugin_render_alert( $attributes ) {
$message = isset( $attributes['message'] ) ? sanitize_text_field( $attributes['message'] ) : '';
return '' . esc_html( $message ) . '
';
}
```
### Mistake 2 — `register_rest_field` update_callback with no capability check
```php
// ❌ Insecure: any authenticated user can update the field.
register_rest_field( 'post', 'my_plugin_meta', array(
'get_callback' => function ( $object ) {
return get_post_meta( $object['id'], '_my_plugin_meta', true );
},
'update_callback' => function ( $value, $object ) {
update_post_meta( $object->ID, '_my_plugin_meta', $value );
},
) );
```
```php
// ✅ Secure: check capability before updating; sanitize value.
register_rest_field(
'post',
'my_plugin_meta',
array(
'get_callback' => function ( $object ) {
return get_post_meta( $object['id'], '_my_plugin_meta', true );
},
'update_callback' => function ( $value, $object ) {
if ( ! current_user_can( 'edit_post', $object->ID ) ) {
return new WP_Error( 'forbidden', __( 'You cannot edit this post.', 'my-plugin' ), array( 'status' => 403 ) );
}
update_post_meta( $object->ID, '_my_plugin_meta', sanitize_text_field( $value ) );
return true;
},
'schema' => array(
'type' => 'string',
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
),
)
);
```
### Mistake 3 — Storing raw RichText without `wp_kses_post`
```php
// ❌ Insecure: RichText can contain script tags and event handlers.
update_post_meta( $post_id, '_my_plugin_note', $attributes['note'] );
```
```php
// ✅ Secure: constrain rich markup.
$note = isset( $attributes['note'] ) ? wp_kses_post( $attributes['note'] ) : '';
update_post_meta( $post_id, '_my_plugin_note', $note );
```
### Mistake 4 — `ServerSideRender` of privileged data without checks
```php
// ❌ Insecure: block preview reveals data the editor user may not be allowed to see.
function my_plugin_render_private( $attributes ) {
return '' . get_option( 'my_plugin_secret_report' ) . '
';
}
```
```php
// ✅ Secure: enforce the same capability in render_callback.
function my_plugin_render_private( $attributes ) {
if ( ! current_user_can( 'manage_options' ) ) {
return '' . esc_html__( 'You do not have permission to view this.', 'my-plugin' ) . '
';
}
$report = get_option( 'my_plugin_secret_report', '' );
return '' . esc_html( $report ) . '
';
}
```
### Mistake 5 — Manual `fetch` without nonce
```js
// ❌ Insecure: custom fetch to a REST endpoint without the nonce.
fetch( '/wp-json/my-plugin/v1/data' )
.then( r => r.json() );
```
```js
// ✅ Secure: use apiFetch, which attaches X-WP-Nonce automatically.
import apiFetch from '@wordpress/api-fetch';
apiFetch( { path: 'my-plugin/v1/data' } )
.then( data => { /* ... */ } );
```
### Mistake 6 — Trusting `postMessage` and raw HTML in editor code
```js
// ❌ Insecure: any window (an embedded preview, an ad iframe, an opener) can
// post a message, and its HTML is rendered unsanitized in the editor.
window.addEventListener( 'message', ( event ) => {
setAttributes( { html: event.data.html } );
} );
// ...
{ attributes.html }
```
```js
// ✅ Secure: check origin and shape, and never render untrusted markup raw.
window.addEventListener( 'message', ( event ) => {
if ( event.origin !== window.location.origin || typeof event.data?.text !== 'string' ) {
return;
}
setAttributes( { text: event.data.text } );
} );
// Render as text (React escapes it), and sanitize server-side on render.
```
Treat `RawHTML`, `dangerouslySetInnerHTML`, `innerHTML`, and jQuery `.html()` as sinks
in admin and editor JavaScript. Deep-merging settings from URL parameters, storage, or
messages into objects (`Object.assign`, `lodash.merge`) can pollute prototypes; reject
`__proto__`, `constructor`, and `prototype` keys.
## Correct code examples
A secure dynamic block with `render_callback` and a REST field with permission checks
is in [`references/secure-block-editor.php`](references/secure-block-editor.php).
## Checklist
- [ ] Block attributes are declared in `block.json` with types and defaults.
- [ ] `render_callback` sanitizes every attribute before use.
- [ ] Server-rendered output is escaped for its context.
- [ ] `register_rest_field()` used by the block has schema + sanitize/validate callbacks.
- [ ] `register_rest_field()` `update_callback` checks the appropriate capability.
- [ ] `RichText` and rich markup are constrained with `wp_kses_post()` or a custom allowlist.
- [ ] `ServerSideRender` blocks enforce the same permissions as the front-end render.
- [ ] Editor JS uses `apiFetch` (or sends `X-WP-Nonce`) for same-site REST calls.
- [ ] No secrets are returned to the block editor for low-privilege users.
- [ ] `message` listeners verify `event.origin` against an allowlist and validate the payload shape.
- [ ] `RawHTML` / `dangerouslySetInnerHTML` / `innerHTML` never receive user- or message-controlled markup.
- [ ] Settings deep-merged from URLs, storage, or messages reject `__proto__`, `constructor`, and `prototype` keys.
## Official references
- [Block Editor Handbook](https://developer.wordpress.org/block-editor/)
- [`register_block_type()`](https://developer.wordpress.org/reference/functions/register_block_type/)
- [`register_rest_field()`](https://developer.wordpress.org/reference/functions/register_rest_field/)
- [`get_block_wrapper_attributes()`](https://developer.wordpress.org/reference/functions/get_block_wrapper_attributes/)
- [`wp_kses_post()`](https://developer.wordpress.org/reference/functions/wp_kses_post/)
- [`esc_html()`](https://developer.wordpress.org/reference/functions/esc_html/)
- [`esc_attr()`](https://developer.wordpress.org/reference/functions/esc_attr/)
- [`current_user_can()`](https://developer.wordpress.org/reference/functions/current_user_can/)
- [WordPress `apiFetch` package](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-api-fetch/)
- [ServerSideRender component](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-server-side-render/)
## Dónde encaja
- Categoría: [Seguridad](https://skillsagentes.com/categorias/seguridad.md) — Auditorías, revisión de dependencias, manejo de secretos y modelado de amenazas.
- Creador: [wpultimatesecurity](https://skillsagentes.com/creators/wpultimatesecurity.md) — 27 skills en el directorio
- [Todas las skills](https://skillsagentes.com/skills.md)
- [Ranking de instalaciones](https://skillsagentes.com/ranking.md)
## Otras skills del mismo repositorio
- [Security Auditing Code Review](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/security-auditing-code-review.md): Ú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.
- [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Ú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.
- [Dependency Supply Chain Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/dependency-supply-chain-security.md): Ú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.
- [Secure Plugin Development](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/secure-plugin-development.md): Ú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.
- [Multisite Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/multisite-security.md): Ú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.
## Skills relacionadas
- [Ai Llm Integration Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ai-llm-integration-security.md): Ú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.
- [Ajax Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ajax-security.md): Ú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.
- [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Ú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.
- [Capability Permission Checks](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/capability-permission-checks.md): Protege operaciones privilegiadas en WordPress con current_user_can() usando la capability correcta (no el rol), checks por objeto y nonce, evitando escalada de privilegios y control de acceso roto.
- [Cron Background Job Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/cron-background-job-security.md): Úsalo al programar eventos cron con wp_schedule_event / wp_schedule_single_event o al escribir el callback. Revalida la autorización contra el contexto guardado, no con current_user_can, y mantiene los secretos fuera de las URLs de cron.
---
Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)