Skip to content

Commit 996cb37

Browse files
committed
CSP: Workaround for ws:// protocol
The spec allows wss:// for 'self', but not ws:// :(
1 parent 0cbdc85 commit 996cb37

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

app.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,15 @@ app.use((req, res, next) => {
116116

117117
// use Content-Security-Policy to limit XSS, dangerous plugins, etc.
118118
// https://helmetjs.github.io/docs/csp/
119+
function getCspNonce (req, res) {
120+
return "'nonce-" + res.locals.nonce + "'"
121+
}
122+
123+
function getCspWebSocketUrl (req, res) {
124+
// wss: is included in 'self', but 'ws:' is not
125+
return (req.protocol === 'http' ? 'ws:' : 'wss:') + config.serverurl.replace(/https?:/, "")
126+
}
127+
119128
if (config.csp.enable) {
120129
var cdnDirectives = {
121130
scriptSrc: ['https://cdnjs.cloudflare.com', 'https://cdn.mathjax.org'],
@@ -125,14 +134,15 @@ if (config.csp.enable) {
125134
var directives = {}
126135
for (var propertyName in config.csp.directives) {
127136
if (config.csp.directives.hasOwnProperty(propertyName)) {
128-
var directive = config.csp.directives[propertyName]
137+
var directive = [].concat(config.csp.directives[propertyName])
129138
if (config.usecdn && !!cdnDirectives[propertyName]) {
130139
directive = directive.concat(cdnDirectives[propertyName])
131140
}
132141
directives[propertyName] = directive
133142
}
134143
}
135-
directives.scriptSrc.push(function (req, res) { return "'nonce-" + res.locals.nonce + "'" })
144+
directives.scriptSrc.push(getCspNonce)
145+
directives.connectSrc.push(getCspWebSocketUrl)
136146
if (config.csp.upgradeInsecureRequests === 'auto') {
137147
directives.upgradeInsecureRequests = config.usessl === 'true'
138148
} else {

0 commit comments

Comments
 (0)