Логотип Gutenberg Block Editor Security

Gutenberg Block Editor Security

Організація
wpultimatesecurity
gutenberg-block-editor-security

Використовуйте під час створення динамічних блоків або функцій редактора блоків: render_callback, блоків із серверним рендерингом через ServerSideRender, даних блоків на основі REST або register_rest_field для редактора. Санітизуйте атрибути блоків відповідно до їхнього типу, екрануйте вивід серверного рендерингу, задавайте справжній permission_callback для REST-інтерфейсів редактора та обробляйте вміст RichText за допомогою wp_kses. Це запобігає збереженому XSS і порушенням контролю доступу в редакторі.

Add to TypingMind

Огляд

Видавецьwpultimatesecurity
РепозиторійWordPress-Security-Skills
Назва навичкиgutenberg-block-editor-security
Зірки
54
Форки
3
Файли в пакеті
2
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 2

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: wpultimatesecurity. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Gutenberg Block Editor Security у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/gutenberg-block-editor-security
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wpultimatesecurity/WordPress-Security-Skills.git /tmp/WordPress-Security-Skills
mkdir -p .claude/skills
cp -r /tmp/WordPress-Security-Skills/skills/gutenberg-block-editor-security .claude/skills/gutenberg-block-editor-security
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Gutenberg Block Editor Security в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Gutenberg Block Editor Security, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Gutenberg Block Editor Security не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

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

ReferenceLoad when
Gutenberg block editor security checklistBefore final verification of the gutenberg block editor security controls.
Secure block editor integrationImplementing 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 '<div class="alert">' . $attributes['message'] . '</div>';
}
php
// ✅ Secure: sanitize and escape the attribute.
function my_plugin_render_alert( $attributes ) {
    $message = isset( $attributes['message'] ) ? sanitize_text_field( $attributes['message'] ) : '';
    return '<div class="alert">' . esc_html( $message ) . '</div>';
}

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 '<pre>' . get_option( 'my_plugin_secret_report' ) . '</pre>';
}
php
// ✅ Secure: enforce the same capability in render_callback.
function my_plugin_render_private( $attributes ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return '<p>' . esc_html__( 'You do not have permission to view this.', 'my-plugin' ) . '</p>';
    }
    $report = get_option( 'my_plugin_secret_report', '' );
    return '<pre>' . esc_html( $report ) . '</pre>';
}

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 } );
} );
// ...
<RawHTML>{ attributes.html }</RawHTML>
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.

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

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Gutenberg Block Editor Security?

Використовуйте під час створення динамічних блоків або функцій редактора блоків: render_callback, блоків із серверним рендерингом через ServerSideRender, даних блоків на основі REST або register_rest_field для редактора. Санітизуйте атрибути блоків відповідно до їхнього типу, екрануйте вивід серверного рендерингу, задавайте справжній permission_callback для REST-інтерфейсів редактора та обробляйте вміст RichText за допомогою wp_kses. Це запобігає збереженому XSS і порушенням контролю доступу в редакторі.

Навіщо використовувати Gutenberg Block Editor Security у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Gutenberg Block Editor Security — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Gutenberg Block Editor Security у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/gutenberg-block-editor-security. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Gutenberg Block Editor Security?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Gutenberg Block Editor Security?

Зі скількома забажаєте. У TypingMind ви можете використовувати Gutenberg Block Editor Security із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Gutenberg Block Editor Security?

Так. На GitHub цю навичку публікує wpultimatesecurity за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇