Skip to content

Commit

Permalink
Support CSP nonce propagation for injected CSS
Browse files Browse the repository at this point in the history
  • Loading branch information
eligrey committed Oct 18, 2024
1 parent 8ba6152 commit e116e7c
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/transcend-io/consent-manager-ui.git"
},
"homepage": "https://github.com/transcend-io/consent-manager-ui",
"version": "4.18.2",
"version": "4.19.0",
"license": "MIT",
"main": "build/ui",
"files": [
Expand Down
9 changes: 9 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {
secondaryPolicy,
languages,
dismissedViewState = 'Hidden',
nonce
} = settings;

/**
Expand Down Expand Up @@ -200,3 +201,11 @@ function validateConfig(config: ConsentManagerConfig): boolean {

return true;
}

export const CSP_NONCE = nonce;
if (CSP_NONCE) {
const currentScriptDataset = document.currentScript?.dataset;
if (currentScriptDataset) {
delete currentScriptDataset.nonce;
}
}
6 changes: 5 additions & 1 deletion src/consent-manager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
import { App } from './components/App';
import { logger } from './logger';
import { createHTMLElement } from './utils/create-html-element';
import { getMergedConfig } from './config';
import { CSP_NONCE, getMergedConfig } from './config';

// The `transcend` API: methods which we'll create inside Preact and pass back out here via callback
let consentManagerAPI: ConsentManagerAPI | null = null;
Expand Down Expand Up @@ -54,6 +54,10 @@ export const injectConsentManagerApp = async (
// Append UI container to doc to activate style.sheet
(document.documentElement || document).append(consentManager);

if (CSP_NONCE) {
style.nonce = CSP_NONCE;
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
style
.sheet! // 1st rule so subsequent properties are reset
Expand Down
4 changes: 4 additions & 0 deletions src/css.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CSP_NONCE } from './config';
import { getAppContainer } from './consent-manager';
import { logger } from './logger';
import { createHTMLElement } from './utils/create-html-element';
Expand All @@ -13,6 +14,9 @@ export const injectCss = (stylesheetUrl: string): Promise<void> =>
const root = getAppContainer();
if (root && stylesheetUrl) {
const link = createHTMLElement<HTMLLinkElement>('link');
if (CSP_NONCE) {
link.nonce = CSP_NONCE;
}
link.type = 'text/css';
link.rel = 'stylesheet';
link.id = stylesheetUrl;
Expand Down

0 comments on commit e116e7c

Please sign in to comment.