Skip to content

Commit

Permalink
fix(@angular/build): add CSP nonce attribute to script tags when in…
Browse files Browse the repository at this point in the history
…line critical CSS is disabled

Prior to this change when inline critical CSS is disabled CSP `nonce` was not added to script tags.

Closes #28102
  • Loading branch information
alan-agius4 committed Jul 29, 2024
1 parent 3eebdb5 commit 636cb69
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { buildApplication } from '../../index';
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';

describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
describe('Behavior: "CSP Nonce"', () => {
it('should add CSP nonce to scripts when optimization is disabled', async () => {
await harness.modifyFile('src/index.html', (content) =>
content.replace(/<app-root/g, '<app-root ngCspNonce="{% nonce %}" '),
);

harness.useTarget('build', {
...BASE_OPTIONS,
polyfills: [],
optimization: false,
});

const { result } = await harness.executeOnce();
expect(result?.success).toBeTrue();

const indexFileContent = harness.expectFile('dist/browser/index.html').content;
indexFileContent.toContain(
'<script src="main.js" type="module" nonce="{% nonce %}"></script>',
);
indexFileContent.toContain('<app-root ngcspnonce="{% nonce %}"');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export class IndexHtmlGenerator {
this.csrPlugins.push(inlineCriticalCssPlugin(this));
}

this.csrPlugins.push(addNoncePlugin());

// SSR plugins
if (options.generateDedicatedSSRContent) {
this.ssrPlugins.push(addEventDispatchContractPlugin(), addNoncePlugin());
Expand Down

0 comments on commit 636cb69

Please sign in to comment.