Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Make Content Security Policy (CSP) nonce available in template.html #1249

Closed
wants to merge 1 commit 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
4 changes: 3 additions & 1 deletion runtime/src/server/middleware/get_page_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,15 @@ export function get_page_handler(

// users can set a CSP nonce using res.locals.nonce
const nonce_attr = (res.locals && res.locals.nonce) ? ` nonce="${res.locals.nonce}"` : '';
const nonce_value = (res.locals && res.locals.nonce) ? res.locals.nonce : '';

const body = template()
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
.replace('%sapper.scripts%', () => `<script${nonce_attr}>${script}</script>`)
.replace('%sapper.html%', () => html)
.replace('%sapper.head%', () => `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`)
.replace('%sapper.styles%', () => styles);
.replace('%sapper.styles%', () => styles)
.replace('%sapper.cspnonce%', () => nonce_value);

res.statusCode = status;
res.end(body);
Expand Down
1 change: 1 addition & 0 deletions site/content/docs/01-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ This file is a template for responses from the server. Sapper will inject conten
* `%sapper.head%` — HTML representing page-specific `<head>` contents, like `<title>`
* `%sapper.html%` — HTML representing the body of the page being rendered
* `%sapper.scripts%` — script tags for the client-side app
* `%sapper.cspnonce%` — CSP nonce taken from `res.locals.nonce` (see [Content Security Policy (CSP)](docs#Content_Security_Policy_CSP))


### src/routes
Expand Down
8 changes: 7 additions & 1 deletion site/content/docs/12-security.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,11 @@ app.use(sapper.middleware());
Using `res.locals.nonce` in this way follows the convention set by
[Helmet's CSP docs](https://helmetjs.github.io/docs/csp/#generating-nonces).

If a CSP nonce is set via `res.locals.nonce`, you can refer to that value via tag `%sapper.cspnonce%` in `src/template.html`. For instance:

```html
<script nonce="%sapper.cspnonce%" src="..."></script>
```

[Express]: https://expressjs.com/
[Helmet]: https://helmetjs.github.io/
[Helmet]: https://helmetjs.github.io/
58 changes: 58 additions & 0 deletions test/apps/cspnonce/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import svelte from 'rollup-plugin-svelte';

const mode = process.env.NODE_ENV;
const dev = mode === 'development';

const config = require('../../../config/rollup.js');

export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
dev,
hydratable: true,
emitCss: true
}),
resolve()
]
},

server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
generate: 'ssr',
dev
}),
resolve({
preferBuiltins: true
})
],
external: ['sirv', 'polka']
},

serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
})
]
}
};
9 changes: 9 additions & 0 deletions test/apps/cspnonce/src/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as sapper from '@sapper/app';

window.start = () => sapper.start({
target: document.querySelector('#sapper')
});

window.prefetchRoutes = () => sapper.prefetchRoutes();
window.prefetch = href => sapper.prefetch(href);
window.goto = href => sapper.goto(href);
3 changes: 3 additions & 0 deletions test/apps/cspnonce/src/routes/_error.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<h1>{status}</h1>

<p>{error.message}</p>
1 change: 1 addition & 0 deletions test/apps/cspnonce/src/routes/index.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Great success!</h1>
13 changes: 13 additions & 0 deletions test/apps/cspnonce/src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import polka from 'polka';
import * as sapper from '@sapper/server';

import { start } from '../../common.js';

const app = polka()
.use((req, res, next) => {
res.locals = { nonce: "rAnd0m123"};
next();
})
.use(sapper.middleware());

start(app);
82 changes: 82 additions & 0 deletions test/apps/cspnonce/src/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as sapper from '@sapper/service-worker';

const ASSETS = `cache${sapper.timestamp}`;

// `shell` is an array of all the files generated by webpack,
// `files` is an array of everything in the `static` directory
const to_cache = sapper.shell.concat(sapper.files);
const cached = new Set(to_cache);

self.addEventListener('install', event => {
event.waitUntil(
caches
.open(ASSETS)
.then(cache => cache.addAll(to_cache))
.then(() => {
self.skipWaiting();
})
);
});

self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(async keys => {
// delete old caches
for (const key of keys) {
if (key !== ASSETS) await caches.delete(key);
}

self.clients.claim();
})
);
});

self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;

const url = new URL(event.request.url);

// don't try to handle e.g. data: URIs
if (!url.protocol.startsWith('http')) return;

// ignore dev server requests
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;

// always serve assets and webpack-generated files from cache
if (url.host === self.location.host && cached.has(url.pathname)) {
event.respondWith(caches.match(event.request));
return;
}

// for pages, you might want to serve a shell `index.html` file,
// which Sapper has generated for you. It's not right for every
// app, but if it's right for yours then uncomment this section
/*
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
event.respondWith(caches.match('/index.html'));
return;
}
*/

if (event.request.cache === 'only-if-cached') return;

// for everything else, try the network first, falling back to
// cache if the user is offline. (If the pages never change, you
// might prefer a cache-first approach to a network-first one.)
event.respondWith(
caches
.open(`offline${sapper.timestamp}`)
.then(async cache => {
try {
const response = await fetch(event.request);
cache.put(event.request, response.clone());
return response;
} catch(err) {
const response = await cache.match(event.request);
if (response) return response;

throw err;
}
})
);
});
16 changes: 16 additions & 0 deletions test/apps/cspnonce/src/template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset='utf-8'>

%sapper.base%
%sapper.styles%
%sapper.head%
</head>
<body>
<div id='sapper'>%sapper.html%</div>
<!-- nonce should be 'rAnd0m123'; cf., server.js -->
<script id="hasNonce" nonce="%sapper.cspnonce%"></script>
%sapper.scripts%
</body>
</html>
26 changes: 26 additions & 0 deletions test/apps/cspnonce/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as assert from 'assert';
import { build } from '../../../api';
import { AppRunner } from '../AppRunner';

describe('cspnonce', function() {
this.timeout(10000);

let r: AppRunner;

// hooks
before('build app', () => build({ cwd: __dirname }));
before('start runner', async () => {
r = await new AppRunner().start(__dirname);
});

after(() => r && r.end());

it('sapper.cspnonce replaced with CSP nonce \'rAnd0m123\' injected via \'res.locals.nonce\'', async () => {
await r.load('/');

assert.equal(
await r.page.$eval('#hasNonce', node => node.getAttribute('nonce')), 'rAnd0m123'
);
});

});