Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(security): add nonce support for injected style tags #1001

Merged
merged 2 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ dist

# TernJS port file
.tern-port

# IntelliJ
.idea/
20 changes: 17 additions & 3 deletions packages/core/src/sheet.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getNonce } from './utility/getNonce'

/** @typedef {import('./sheet').RuleGroup} RuleGroup */
/** @typedef {import('./sheet').RuleGroupNames} RuleGroupNames */
/** @typedef {import('./sheet').SheetGroup} SheetGroup */
Expand Down Expand Up @@ -137,8 +139,20 @@ export const createSheet = (/** @type {DocumentOrShadowRoot} */ root) => {
})
}

const createSheet = () => {
if (!root) {
return createCSSMediaRule('', 'text/css')
}
const styleEl = document.createElement('style')
const nonce = getNonce()
if (nonce) {
styleEl.setAttribute('nonce', nonce)
}
return (root.head || root).appendChild(styleEl).sheet
}

groupSheet = {
sheet: root ? (root.head || root).appendChild(document.createElement('style')).sheet : createCSSMediaRule('', 'text/css'),
sheet: createSheet(),
rules: {},
reset,
toString,
Expand Down Expand Up @@ -187,9 +201,9 @@ const addApplyToGroup = (/** @type {RuleGroup} */ group) => {
/** Pending rules for injection */
const $pr = Symbol()

/**
/**
* When a stitches component is extending some other random react component,
* it’s gonna create a react component (Injector) using this function and then render it after the children,
* it’s gonna create a react component (Injector) using this function and then render it after the children,
* this way, we would force the styles of the wrapper to be injected after the wrapped component
*/
export const createRulesInjectionDeferrer = (globalSheet) => {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/utility/getNonce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const getNonce = () => {
if (typeof window.__webpack_nonce__ !== 'undefined') return window.__webpack_nonce__
if (typeof window.nonce !== 'undefined') return window.nonce
return null
}