Skip to content

fix: avoid TrustedHTML sink for style injection - #809

Open
nrps9909 wants to merge 1 commit into
react-component:masterfrom
nrps9909:codex/trusted-types-style-text
Open

nrps9909 wants to merge 1 commit into
react-component:masterfrom
nrps9909:codex/trusted-types-style-text

Conversation

@nrps9909

@nrps9909 nrps9909 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #555.

injectCSS and the existing-node path in updateCSS use HTMLStyleElement.innerHTML, which throws when the host document enforces Trusted Types. Writing and comparing CSS through textContent allows stylesheet injection and updates under that policy without a TrustedHTML policy.

The regression blocks the style innerHTML setter and covers initial injection and updates to an existing managed style. The patch is based on current master 993255ed15595875a7004033c3e8f7b892586dea; the recently merged missing-container guards and their tests are retained. Only the original two files change (38 insertions, 3 deletions).

Validation on Node 26.10.0, pnpm 11.21.0, TypeScript 6.0.3:

  • Current master with the new regression: 1 failure at the TrustedHTML sink, 209 passes, 1 existing skip. Fixed source: all 31 suites pass, 210 tests pass, 1 skip.
  • A separate Chromium 151.0.7922.34 probe uses an actual HTTP CSP header: require-trusted-types-for 'script'; trusted-types 'none'. Both initial injection and preexisting-node updates throw on base and pass after the fix. The unsafe-setter control stays blocked in both versions. CSS text/computed color, nonce, node identity and no duplicate managed styles are verified.
  • TypeScript, ESM/CJS/declaration compilation, focused ESLint (0 errors, 1 existing unused-disable warning), Prettier and diff checks pass.

These are local results; upstream CI and maintainer review remain separate, and this PR is still open.

AI assistance disclosure: Codex helped trace the sink, resolve the upstream test conflict, run base/head validation and the independent Chromium probe, and prepare this description. The final diff and results were checked against the recorded commits.

Summary by CodeRabbit

  • Bug Fixes

    • 改进动态样式的注入与更新,提升在严格内容安全策略环境中的兼容性。
    • 样式内容按纯文本写入,避免受 HTML 内容限制影响。
  • Tests

    • 新增测试,验证受限环境下样式可正常注入和更新。

@vercel

vercel Bot commented Aug 27, 2026

Copy link
Copy Markdown

@nrps9909 is attempting to deploy a commit to the afc163's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: ed327798-ada0-42a7-9bfb-8c20d3beeadd

📥 Commits

Reviewing files that changed from the base of the PR and between 5c6618f and fd34914.

📒 Files selected for processing (2)
  • src/Dom/dynamicCSS.ts
  • tests/dynamicCSS.test.tsx

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.


Walkthrough

动态 CSS 注入和更新改用 textContent。新增测试模拟 innerHTML setter 抛出 TypeError 的环境,并检查样式内容的写入和更新。

Changes

动态 CSS 兼容性

Layer / File(s) Summary
样式写入与兼容性验证
src/Dom/dynamicCSS.ts, tests/dynamicCSS.test.tsx
injectCSS 和 updateCSS 使用 textContent 写入和比较 CSS。测试模拟 innerHTML setter 抛出 TypeError,并在测试结束后恢复原有属性描述符,或删除临时属性。

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to fd349

The change avoids TrustedHTML restrictions during stylesheet injection while preserving CSS text and existing update behavior. No actionable merge-blocking risk remains in the supplied evidence.

Security Architecture Review

Security architecture risk: 🔵 Low · up to fd349

The change treats stylesheet content as text while preserving existing style ownership, insertion order, and CSP nonce handling. No introduced security defect is established. Downstream CSS trust policies and behavior under actual browser policy enforcement remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated effect is on styles installed in the caller-selected DOM container. Existing helpers can now succeed where TrustedHTML enforcement previously rejected their writes; broader exposure depends on downstream callers and policies not supplied here.

Trust Boundaries and Controls

  • observed — The change removes HTML parsing and the TrustedHTML assignment gate from CSS writes. It does not introduce CSS sanitization or change who supplies CSS, container options, keys, or nonces. Nonce handling is unchanged; textContent should not be interpreted as establishing that arbitrary CSS is trusted.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed PR #809 满足直接关联问题 #555 的编码要求。src/Dom/dynamicCSS.ts 将 injectCSS 和 updateCSS 的样式内容写入及比较从 innerHTML 改为 textContent,因此不再使用触发 TrustedHTML 要求的 HTML sink。新增回归测试覆盖初始注入和已有样式节点更新,并验证样式内容仍然正确保留。
Out of Scope Changes check ✅ Passed 变更仅涉及动态样式注入实现和对应的 Trusted Types 回归测试。测试直接验证问题 #555 的修复。未发现与该问题无关的代码、配置或文档变更。
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确概括了主要变更:避免样式注入使用 TrustedHTML sink。该描述与将 innerHTML 替换为 textContent 的代码变更和测试目标一致。
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

小兔写入 textContent,
样式文本落入节点。
setter 抛出 TypeError,
注入更新仍可完成。
测试结束恢复属性,
月光照着 CSS。

Comment @coderabbitai help to get the list of available commands.

@nrps9909
nrps9909 force-pushed the codex/trusted-types-style-text branch from 5c6618f to fd34914 Compare October 1, 2026 02:11
@nrps9909

nrps9909 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the conflict against current master 993255ed15595875a7004033c3e8f7b892586dea at signed/GitHub-Verified head fd34914bed881cfc51f54d8b10f1c03aa3ca0c0a. The original two-file patch is retained; the new missing-container guards and regressions from #811 are preserved.

Rechecked base/head: the TrustedHTML regression fails on base (209 other tests pass), while the fix passes all 31 suites / 210 tests with one existing skip. TypeScript, ESM/CJS/declaration builds, focused lint (0 errors, 1 existing warning), formatting and diff checks pass.

An independent Chromium 151.0.7922.34 probe with an actual require-trusted-types-for 'script'; trusted-types 'none' HTTP header reproduces both initial-injection and existing-node update failures on base. Both pass after the fix; CSS/computed color, nonce, node reuse and absence of duplicate styles are checked, while an unsafe innerHTML control remains blocked in both versions. Local evidence is separate from upstream CI/review. AI assistance: Codex helped resolve the test conflict and run these validations.

@codecov

codecov Bot commented Oct 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.94%. Comparing base (993255e) to head (fd34914).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #809   +/-   ##
=======================================
  Coverage   86.94%   86.94%           
=======================================
  Files          41       41           
  Lines        1111     1111           
  Branches      404      396    -8     
=======================================
  Hits          966      966           
  Misses        143      143           
  Partials        2        2           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

injectCSS throw This document requires 'TrustedHTML' assignment.

1 participant