Skip to content

feat: Add nonce support for css-variables - #255

Merged
zombieJ merged 3 commits into
masterfrom
feat/css-variable-update
Mar 4, 2026
Merged

feat: Add nonce support for css-variables#255
zombieJ merged 3 commits into
masterfrom
feat/css-variable-update

Conversation

@zombieJ

@zombieJ zombieJ commented Mar 4, 2026

Copy link
Copy Markdown
Member

Summary

This PR adds CSP nonce support for better security when using CSS variables in cssinjs.

Changes

  • Extract injectCSPNonce helper: New utility function to unify nonce injection logic across all hooks
  • useCacheToken: Add nonce parameter support with TypeScript type definition (string or (() => string))
  • useCSSVarRegister: Add nonce parameter support
  • useStyleRegister: Refactor to use the new injectCSPNonce helper instead of inline nonce handling
  • Tests: Add comprehensive test coverage for nonce functionality in both useCacheToken and useCSSVarRegister hooks

Benefits

  • Provides Content Security Policy (CSP) nonce support for style elements
  • Unifies nonce handling logic across all hooks for better maintainability
  • Supports both static string and dynamic function nonce values
  • Fully tested with comprehensive test cases

Example Usage

useCacheToken(
  theme,
  [defaultDesignToken],
  {
    salt: '',
    cssVar: {
      prefix: 'rc',
      key: 'my-theme',
    },
    nonce: 'my-nonce-value', // or nonce: () => dynamicNonce()
  }
);

Summary by CodeRabbit

发布说明

  • 新功能

    • CSS变量注册、缓存令牌和样式注册现已支持CSP(内容安全策略)nonce配置选项,提供更强的安全性保护。
  • 测试

    • 添加了针对nonce功能的完整测试覆盖,验证字符串和函数两种nonce形式的正确工作。

- Extract injectCSPNonce helper function to unify nonce injection logic
- Add nonce parameter support to useCacheToken hook with type definition
- Add nonce parameter support to useCSSVarRegister hook
- Refactor useStyleRegister to use new injectCSPNonce helper
- Add comprehensive tests for nonce functionality (string and function types)

This provides better CSP security by allowing nonce configuration for style elements.
@coderabbitai

coderabbitai Bot commented Mar 4, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@zombieJ has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 21 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7daf2e8c-1087-4fd7-82f7-a9dc34b75763

📥 Commits

Reviewing files that changed from the base of the PR and between a43d123 and ede79c0.

📒 Files selected for processing (4)
  • src/hooks/useCSSVarRegister.ts
  • src/hooks/useCacheToken.tsx
  • src/hooks/useStyleRegister.tsx
  • src/util/index.ts
📝 Walkthrough

Walkthrough

该拉取请求在CSS变量注册流程中添加了CSP随机数(nonce)支持。通过引入新的Nonce类型和injectCSPNonce辅助函数,在useCSSVarRegister、useCacheToken和useStyleRegister等hooks中注入CSP nonce,并为相关场景添加了测试用例。

Changes

Cohort / File(s) Summary
CSS Variable Registration Hooks
src/hooks/useCSSVarRegister.ts, src/hooks/useCacheToken.tsx, src/hooks/useStyleRegister.tsx
添加可选的nonce配置参数(string或function类型),通过injectCSPNonce辅助函数将nonce注入到CSS更新配置中。useStyleRegister用新辅助函数替换了手工nonce处理逻辑。
Utility Module
src/util/index.ts
引入新的Nonce类型定义和injectCSPNonce函数,用于计算nonce字符串值并将其安全地注入到CSS配置的csp.nonce属性中。
Test Suite
tests/css-variables.spec.tsx
新增nonce测试套件,覆盖useCacheToken和useCSSVarRegister两条路径,验证nonce参数接受字符串或函数形式,并确保生成的style元素正确附带nonce值。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 小兔来贺,nonce添新装,
CSP策略更安常,
字符串或函数任君选,
注入利落不迷茫。

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title clearly and accurately summarizes the main change: adding nonce support for CSS variables. It is concise, specific, and directly reflects the primary objective of the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/css-variable-update

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

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

@github-actions

github-actions Bot commented Mar 4, 2026

Copy link
Copy Markdown

🎊 PR Preview ede79c0 has been successfully built and deployed to https://ant-design-cssinjs-preview-pr-255.surge.sh

🕐 Build time: 99.856s

🤖 By surge-preview

@codecov

codecov Bot commented Mar 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.74%. Comparing base (d1cbe07) to head (ede79c0).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #255      +/-   ##
==========================================
+ Coverage   94.65%   94.74%   +0.09%     
==========================================
  Files          32       32              
  Lines        2823     2873      +50     
  Branches      448      450       +2     
==========================================
+ Hits         2672     2722      +50     
  Misses        151      151              

☔ View full report in Codecov by Sentry.
📢 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.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the security posture of the cssinjs library by integrating Content Security Policy (CSP) nonce support for dynamically injected CSS variables. The changes streamline nonce management through a new helper function and extend this capability to key styling hooks, ensuring consistent and secure style injection.

Highlights

  • CSP Nonce Support: Implemented Content Security Policy (CSP) nonce support for CSS variables within cssinjs to enhance security.
  • injectCSPNonce Helper: Introduced a new injectCSPNonce utility function to centralize and unify nonce injection logic across various hooks.
  • nonce Parameter: Added nonce parameter support to useCacheToken and useCSSVarRegister hooks, accepting both string and function types.
  • useStyleRegister Refactor: Refactored useStyleRegister to utilize the new injectCSPNonce helper, replacing its previous inline nonce handling.
  • Test Coverage: Added comprehensive test cases to validate the new nonce functionality in useCacheToken and useCSSVarRegister.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/hooks/useCSSVarRegister.ts
    • Imported injectCSPNonce from ../util.
    • Added nonce?: string | (() => string); to the configuration interface.
    • Destructured nonce from the config object.
    • Integrated injectCSPNonce to apply CSP nonce to the updateCSS configuration.
  • src/hooks/useCacheToken.tsx
    • Imported injectCSPNonce from ../util.
    • Added nonce?: string | (() => string); to the Option interface with JSDoc.
    • Destructured nonce from the option object.
    • Integrated injectCSPNonce to apply CSP nonce to the updateCSS configuration.
  • src/hooks/useStyleRegister.tsx
    • Imported injectCSPNonce from ../util.
    • Replaced the manual nonce extraction and csp configuration logic with a call to injectCSPNonce.
  • src/util/index.ts
    • Defined Nonce type as string | (() => string).
    • Implemented injectCSPNonce function to extract nonce from a string or function and apply it to a configuration object's csp property.
  • tests/css-variables.spec.tsx
    • Imported ATTR_TOKEN from ../src/StyleContext.
    • Added a new describe('nonce', ...) block containing tests for useCacheToken and useCSSVarRegister to verify nonce application with both string and function values.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces CSP nonce support for CSS variables, which is a great security enhancement. The changes are well-structured: a new injectCSPNonce utility is created to centralize the logic, and this helper is used consistently across useCacheToken, useCSSVarRegister, and useStyleRegister. The addition of comprehensive tests for the nonce functionality is also a valuable contribution. I have one minor suggestion to make the new injectCSPNonce helper more robust for future use.

Comment thread src/util/index.ts Outdated
zombieJ and others added 2 commits March 4, 2026 23:50
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
- Change injectCSPNonce from mutating to returning new object
- Follow functional programming principles
- Preserve existing csp config with spread operator
- Update all call sites to use returned value
@zombieJ
zombieJ merged commit bf6b2d1 into master Mar 4, 2026
8 checks passed
@zombieJ
zombieJ deleted the feat/css-variable-update branch March 4, 2026 15:57
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.

1 participant