Логотип Rendering Untrusted Content

Rendering Untrusted Content

Спільнота
wdm0006
rendering-untrusted-content

Перетворюйте збережений, створений або імпортований вміст на HTML, не допускаючи XSS: перевіряйте кожен обхід автоматичного екранування (`|safe`, Markup, innerHTML), очищуйте результат Markdown за списком дозволених елементів, екрануйте дані і на сервері, і в DOM, а в тестах очищення перевіряйте правильну копію рядка. Використовуйте навичку, коли додаєте фільтр Markdown або форматованого тексту, відображаєте вміст, створений користувачем чи адміністратором, перевіряєте шаблон, що позначає HTML як довірений, створюєте клієнт, який вставляє значення в innerHTML, або виправляєте повідомлення про XSS.

Add to TypingMind

Огляд

Видавецьwdm0006
Репозиторійpython-skills
Назва навичкиrendering-untrusted-content
Зірки
111
Форки
17
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

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

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

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

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

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

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

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

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

1

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

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

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/wdm0006/python-skills/tree/main/skills/common/rendering-untrusted-content
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

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

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

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wdm0006/python-skills.git /tmp/python-skills
mkdir -p .claude/skills
cp -r /tmp/python-skills/skills/common/rendering-untrusted-content .claude/skills/rendering-untrusted-content
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

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

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

Модель самостійно завантажує навичку Rendering Untrusted Content, щойно надходить відповідний запит.

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

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

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

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

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

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

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

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

Rendering Untrusted Content

Template engines autoescape by default, so the vulnerable surface is small and enumerable: it is exactly the places where something says this value is already safe HTML. Find those first; everything else is already handled.

Step 1 — Enumerate the trust bypasses

bash
# Server-side (Jinja/Django templates + the Python that feeds them)
grep -rnE '\|\s*safe|Markup\(|autoescape false|mark_safe' templates/ src/

# Client-side
grep -rnE 'innerHTML|outerHTML|insertAdjacentHTML|document\.write' web/ static/

Every hit is a claim that needs justification. A |safe on a value that came from a database column is a claim about everything that has ever been written to that column, including via an import path nobody remembers.

Step 2 — Markdown output is not sanitized HTML

Markdown renderers pass raw HTML through by design — that is a documented feature, not a bug. So a shared template filter shaped like this is an XSS sink:

python
# BAD — the filter marks arbitrary stored markup trusted.
def _markdown(text: str) -> Markup:
    return Markup(markdown.markdown(text, extensions=["extra", "tables"]))

"Only admins author content" is not a boundary. As soon as there is an import path, a seed script, or a second author, the content store is untrusted input.

Render, then sanitize with an allowlist, and only then mark trusted:

python
import markdown, nh3
from markupsafe import Markup

ALLOWED_TAGS = {
    "p", "br", "hr", "em", "strong", "code", "pre", "blockquote",
    "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li",
    "a", "img", "table", "thead", "tbody", "tr", "th", "td",
}
ALLOWED_ATTRS = {
    "a": {"href", "title", "rel"},
    "img": {"src", "alt", "title"},
    "th": {"style", "align"},
    "td": {"style", "align"},
}

def _markdown(text: str) -> Markup:
    html = markdown.markdown(text, extensions=["extra", "tables"])
    return Markup(nh3.clean(
        html,
        tags=ALLOWED_TAGS,
        attributes=ALLOWED_ATTRS,
        filter_style_properties={"text-align"},   # see below
    ))

Do not hand-roll the allowlist logic. Use a maintained HTML sanitizer (nh3, the Rust/ammonia-backed successor to bleach). Regex-stripping <script> is not sanitization.

The table-alignment trap

Markdown's tables extension encodes column alignment as an inline style — <th style="text-align: left;">. An allowlist that drops style is "secure" and silently removes alignment from every table in the corpus. Allow style on table cells and constrain which properties survive (filter_style_properties).

Then note that the sanitizer normalizes what it keeps: text-align: left; comes back as text-align:left — no space, no trailing semicolon. An exact-output test must expect the normalized form, not the string Markdown emitted, or it fails on a correct fix.

Step 3 — A shared filter has the whole corpus as its blast radius

One filter feeds every post body, every FAQ answer, every description. Changing it re-renders all of them at once, and the failure mode is not a crash — it is content quietly losing a construct.

Render every piece of authored content before and after the change and diff it character by character, then keep that as a regression test:

python
@pytest.mark.parametrize("path", sorted(CONTENT_DIR.glob("*.md")))
def test_authored_content_is_unchanged_by_sanitization(path):
    raw = markdown.markdown(path.read_text(), extensions=EXTENSIONS)
    assert _markdown(path.read_text()) == raw

If no authored file contains raw HTML, that equality holds and any future diff is a genuine regression. If some file does need raw HTML, you have found the one case worth an explicit decision instead of discovering it in production.

Step 4 — Test the copy of the string that actually matters

The same value is often rendered several times on one page: in prose, in <meta> tags, and inside a JSON-LD <script> block. A whole-document assertion therefore reports a vulnerability that isn't one:

python
# BAD — fails even when the prose is correctly sanitized.
assert "<script>alert(1)</script>" not in html

Template tojson filters emit HTML-safe JSON — angle brackets become \u003c / \u003e, so the JSON-LD copy cannot break out of its <script> element and is not a vulnerability. But the payload's text still appears there, so a document-wide assertion goes red while the prose is perfectly sanitized. Scope the assertion to the rendered prose:

python
article = extract_article_html(html)
assert "<script>" not in article
assert "&lt;script&gt;" in article        # proves it was escaped, not dropped

Assert the escaped form is present, not just that the dangerous form is absent — otherwise a filter that silently deletes the whole field passes.

Also scope the audit: a feed or export built from separately-escaped title/description fields that never includes the body is not part of this surface. Don't "fix" it.

Step 5 — Escape at both ends

Server-side escaping does nothing for a client that re-injects the same value through innerHTML. A card grid rendered safely by the server and a detail modal built with a template literal are two independent sinks, and the second one is usually the one that got missed.

js
// Prefer the API that cannot execute markup.
el.textContent = item.description;

// When you must build markup, escape into a local first.
const description = escapeHtml(item.description);
const tags = item.tags.map(escapeHtml).join(", ");
modal.innerHTML = `<p>${description}</p><footer>${tags}</footer>`;

Escaping into a const before the template literal is not just style: wrapping the expression inline pushes the line past the linter's length limit, and reflowing the HTML string to fit introduces leading whitespace that is visible inside white-space: pre-wrap blocks. Escape first, interpolate second.

Step 6 — "No event handlers" is a test that fails on clean code

Asserting that no on* attribute appears in rendered output looks like a strong XSS regression test, and it goes red immediately: application templates legitimately emit handlers (onclick="showDetail(3)"). A test that fails on correct code gets deleted within a week.

Allowlist the handlers your own templates emit and assert on the remainder:

python
handlers = re.findall(r'\son(\w+)="([^"]*)"', card_html)
assert handlers == [("click", "showDetail(3)")]

Pinning the full list (rather than not any(...)) also catches a second, injected handler alongside the legitimate one — presence assertions can't.

Checklist

- [ ] Every |safe / Markup() / mark_safe / innerHTML site enumerated and justified
- [ ] Markdown (and any rich-text) output passes through an allowlist sanitizer
      before being marked trusted — a maintained library, not a regex
- [ ] Allowlist keeps constructs the renderer depends on (table-cell style),
      and tests expect the sanitizer's normalized output
- [ ] Authored content diffed before/after the filter change, pinned by a test
- [ ] Sanitization tests assert on the rendered prose, and assert the escaped
      form is present — not just that the raw payload is absent
- [ ] Client-side injection points escape too (or use textContent)
- [ ] Handler/attribute assertions allowlist what the app's own templates emit

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

Що робить навичка ШІ Rendering Untrusted Content?

Перетворюйте збережений, створений або імпортований вміст на HTML, не допускаючи XSS: перевіряйте кожен обхід автоматичного екранування (`|safe`, Markup, innerHTML), очищуйте результат Markdown за списком дозволених елементів, екрануйте дані і на сервері, і в DOM, а в тестах очищення перевіряйте правильну копію рядка. Використовуйте навичку, коли додаєте фільтр Markdown або форматованого тексту, відображаєте вміст, створений користувачем чи адміністратором, перевіряєте шаблон, що позначає HTML як довірений, створюєте клієнт, який вставляє значення в innerHTML, або виправляєте повідомлення п...

Навіщо використовувати Rendering Untrusted Content у TypingMind?

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

Як встановити Rendering Untrusted Content у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/wdm0006/python-skills/tree/main/skills/common/rendering-untrusted-content. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Rendering Untrusted Content?

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

Зі скількома моделями ШІ можна використовувати Rendering Untrusted Content?

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

Чи безкоштовна навичка ШІ Rendering Untrusted Content?

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

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

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

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

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

Усі
Логотип openclaw

Openclaw Testing

openclaw
ОрганізаціяПопулярне

Добирайте пропорційні за обсягом тести й перевірки OpenClaw, діагностуйте помилки та передавайте завдання, чутливі до середовища, або підтвердження для релізу відповідальним особам.

82.2K
391K
Файлів: 2
Відкрити
Логотип openclaw

Release Openclaw Ci

openclaw
ОрганізаціяПопулярне

Запускайте, відстежуйте, налагоджуйте та підсумовуйте повний CI для релізів OpenClaw, перевірки релізів, контрольні перевірки робочих провайдерів, підтвердження встановлення й оновлення та попередні перевірки секретів для релізу.

82.2K
391K
Файлів: 3
Відкрити
Логотип openclaw

Release Openclaw Mac

openclaw
ОрганізаціяПопулярне

Виконуйте підписування релізів OpenClaw для macOS, нотаризацію, оновлення appcast і просування ресурсів або відновлюйте ці процеси.

82.2K
391K
Інструкції
Відкрити
Логотип openclaw

Release Openclaw Maintainer

openclaw
ОрганізаціяПопулярне

Готуйте, публікуйте, відновлюйте або перевіряйте бета-, стабільні й розширено стабільні релізи OpenClaw, зокрема затверджені зворотні перенесення змін.

82.2K
391K
Файлів: 11
Відкрити

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

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