Skip to content

Commit

Permalink
ensure csphtml plugin runs after all other plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
ashtonG committed Feb 6, 2023
1 parent e2335c1 commit f6d10b6
Showing 1 changed file with 36 additions and 33 deletions.
69 changes: 36 additions & 33 deletions webui/react/src/shared/configs/vite-plugin-csp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,40 +21,43 @@ interface CspHtmlPluginConfig {

export const cspHtml = ({ cspRules, hashEnabled = {} }: CspHtmlPluginConfig): Plugin => ({
name: 'csp-html',
async transformIndexHtml(html: string) {
const finalCspRules: CspRuleConfig = {
'base-uri': ["'self'"],
...cspRules,
};
const hashRules = Object.entries(hashEnabled) as [CspHashDirective, boolean][];
if (hashRules.length) {
const cheerio = await import('cheerio');
const $ = cheerio.load(html);
hashRules.forEach(([directive, enabled]: [CspHashDirective, boolean]) => {
if (!enabled) return;
const [tag] = directive.split('-');
$(tag).each((_, el) => {
const source = $(el).html();
if (source) {
const hash = crypto.createHash('sha256').update(source).digest('base64');
finalCspRules[directive] = (finalCspRules[directive] || []).concat([
`'sha256-${hash}'`,
]);
}
transformIndexHtml: {
async handler(html: string) {
const finalCspRules: CspRuleConfig = {
'base-uri': ["'self'"],
...cspRules,
};
const hashRules = Object.entries(hashEnabled) as [CspHashDirective, boolean][];
if (hashRules.length) {
const cheerio = await import('cheerio');
const $ = cheerio.load(html);
hashRules.forEach(([directive, enabled]: [CspHashDirective, boolean]) => {
if (!enabled) return;
const [tag] = directive.split('-');
$(tag).each((_, el) => {
const source = $(el).html();
if (source) {
const hash = crypto.createHash('sha256').update(source).digest('base64');
finalCspRules[directive] = (finalCspRules[directive] || []).concat([
`'sha256-${hash}'`,
]);
}
});
});
});
}
const content = Object.entries(finalCspRules)
.map(([directive, sources]) => `${directive} ${sources.join(' ')}`)
.join('; ');
return [
{
attrs: {
content,
'http-equiv': 'Content-Security-Policy',
}
const content = Object.entries(finalCspRules)
.map(([directive, sources]) => `${directive} ${sources.join(' ')}`)
.join('; ');
return [
{
attrs: {
content,
'http-equiv': 'Content-Security-Policy',
},
tag: 'meta',
},
tag: 'meta',
},
];
];
},
order: 'post',
},
});

0 comments on commit f6d10b6

Please sign in to comment.