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] Add nonce placeholders in rendered pages. #2391

Closed
wants to merge 4 commits into from
Closed
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
5 changes: 5 additions & 0 deletions .changeset/lovely-rats-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Add option to place CSP nonce placeholders in rendered pages.
49 changes: 49 additions & 0 deletions documentation/docs/15-content-security-policy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: Content Security Policy
---

At the moment, SvelteKit supports adding Content Security Policy via hooks. In environments with a runtime, HTTP headers can be added to the response object.

However, SvelteKit also requires some small pieces of inline JavaScript in order for hydration to work. To avoid using `'unsafe-inline'` (which, as the name suggests, should be avoided), SvelteKit can be configured to inject place-holders for CSP Nonces into the html it generates.

These placeholders take the form `%svelte.CSPNonce%`, and can be replaced with a nonce inside the hook. A basic CSP handler hook might then look like this:
```javascript
export async function handle ({ request, resolve }) => {
const directives = {
'default-src': ["'self'", rootDomain, `ws://${rootDomain}`],
'script-src': ["'strict-dynamic'"],
'style-src': ["'self'"]
};

const response = await resolve(request);

const nonce = randomBytes(32).toString('base64');

if (response.headers['content-type'] === 'text/html') {
response.body = (response.body as string).replace(/%svelte.CSPNonce%/g, `nonce="${nonce}"`);
}
directives['script-src'].push(`'nonce-${nonce}'`);
directives['style-src'].push(`'nonce-${nonce}'`);

if (process.env.NODE_ENV === 'development') {
directives['style-src'].push('unsafe-inline')
}

const csp = Object.entries(directives)
.map(([key, arr]) => key + ' ' + arr.join(' '))
.join('; ');

return {
...response,
headers: {
...response.headers,
'Content-Security-Policy': csp
}
};
};
```
Because of the way Vite performs hot reloads of stylesheets, `'unsafe-inline'` is required in dev mode.

Be warned: some other features of Svelte (in particular CSS transitions and animations) might run afoul of this Content Security Policy and require either rewriting to JS-based transitions or enabling `style-src: 'unsafe-inline'`.

The nonce placeholders can be toggled with the `kit.noncePlaceholders` configuration option.
3 changes: 2 additions & 1 deletion packages/kit/src/core/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ async function build_server(
ssr: ${s(config.kit.ssr)},
target: ${s(config.kit.target)},
template,
trailing_slash: ${s(config.kit.trailingSlash)}
trailing_slash: ${s(config.kit.trailingSlash)},
noncePlaceholders: ${s(config.kit.noncePlaceholders)}
};
}

Expand Down
6 changes: 4 additions & 2 deletions packages/kit/src/core/config/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ test('fills in defaults', () => {
router: true,
ssr: true,
target: null,
trailingSlash: 'never'
trailingSlash: 'never',
noncePlaceholders: false
}
});
});
Expand Down Expand Up @@ -164,7 +165,8 @@ test('fills in partial blanks', () => {
router: true,
ssr: true,
target: null,
trailingSlash: 'never'
trailingSlash: 'never',
noncePlaceholders: false
}
});
});
Expand Down
4 changes: 3 additions & 1 deletion packages/kit/src/core/config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,9 @@ const options = object(

return input;
}
)
),

noncePlaceholders: boolean(false)
})
},
true
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/core/config/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ async function testLoadDefaultConfig(path) {
router: true,
ssr: true,
target: null,
trailingSlash: 'never'
trailingSlash: 'never',
noncePlaceholders: false
}
});
}
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/src/core/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,8 @@ async function create_handler(vite, config, dir, cwd, get_manifest) {

return rendered;
},
trailing_slash: config.kit.trailingSlash
trailing_slash: config.kit.trailingSlash,
noncePlaceholders: config.kit.noncePlaceholders
}
);

Expand Down
17 changes: 10 additions & 7 deletions packages/kit/src/runtime/server/page/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export async function render_response({
const css = new Set(options.entry.css);
const js = new Set(options.entry.js);
const styles = new Set();
const nonce = options.noncePlaceholders ? '%svelte.CSPNonce%' : '';

/** @type {Array<{ url: string, body: string, json: string }>} */
const serialized_data = [];
Expand Down Expand Up @@ -96,10 +97,12 @@ export async function render_response({
// TODO strip the AMP stuff out of the build if not relevant
const links = options.amp
? styles.size > 0 || rendered.css.code.length > 0
? `<style amp-custom>${Array.from(styles).concat(rendered.css.code).join('\n')}</style>`
? `<style ${nonce} amp-custom>${Array.from(styles)
.concat(rendered.css.code)
.join('\n')}</style>`
: ''
: [
...Array.from(js).map((dep) => `<link rel="modulepreload" href="${dep}">`),
...Array.from(js).map((dep) => `<link rel="modulepreload" href="${dep}" ${nonce}>`),
...Array.from(css).map((dep) => `<link rel="stylesheet" href="${dep}">`)
].join('\n\t\t');

Expand All @@ -108,12 +111,12 @@ export async function render_response({

if (options.amp) {
init = `
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
<style ${nonce} amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
<noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>`;
} else if (include_js) {
// prettier-ignore
init = `<script type="module">
init = `<script type="module" ${nonce}>
import { start } from ${s(options.entry.file)};
start({
target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
Expand Down Expand Up @@ -145,7 +148,7 @@ export async function render_response({
}

if (options.service_worker) {
init += `<script>
init += `<script ${nonce}>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('${options.service_worker}');
}
Expand All @@ -155,7 +158,7 @@ export async function render_response({
const head = [
rendered.head,
styles.size && !options.amp
? `<style data-svelte>${Array.from(styles).join('\n')}</style>`
? `<style ${nonce} data-svelte>${Array.from(styles).join('\n')}</style>`
: '',
links,
init
Expand All @@ -170,7 +173,7 @@ export async function render_response({
let attributes = `type="application/json" data-type="svelte-data" data-url="${url}"`;
if (body) attributes += ` data-body="${hash(body)}"`;

return `<script ${attributes}>${json}</script>`;
return `<script ${nonce} ${attributes}>${json}</script>`;
})
.join('\n\n\t')}
`;
Expand Down
1 change: 1 addition & 0 deletions packages/kit/types/config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export interface Config {
target?: string;
trailingSlash?: TrailingSlash;
vite?: ViteConfig | (() => ViteConfig);
noncePlaceholders?: boolean;
};
preprocess?: any;
}
Expand Down
1 change: 1 addition & 0 deletions packages/kit/types/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ export interface SSRRenderOptions {
target: string;
template({ head, body }: { head: string; body: string }): string;
trailing_slash: TrailingSlash;
noncePlaceholders: boolean;
}

export interface SSRRenderState {
Expand Down