Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created September 11, 2019 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRayCode/c01e4a82e5172a5899c1c9131c99864a to your computer and use it in GitHub Desktop.
Save AndrewRayCode/c01e4a82e5172a5899c1c9131c99864a to your computer and use it in GitHub Desktop.
const http = require('http');
const PORT = 8081;
const BROKEN_CSP = [
"default-src 'self'",
"child-src googleads.g.doubleclick.net",
// The below line should work too, but it's not required to trigger the
// bug. The object tag should fall through to default-src 'self'. As in,
// you can comment out the line below, and it will still fail
"object-src 'self'"
].join('; ');
// Setting child-source 'self' seems to be a workaround
const WORKAROUND_CSP = [
"default-src 'self'",
"child-src 'self' googleads.g.doubleclick.net",
].join('; ');
// Path of the embededed object
const PDF_PATH = '/embedded_pdf';
// The object tag that's getting blocked
const OBJECT_TAG = `<object type="application/pdf" data="${PDF_PATH}" width="200px" height="200px"></object>`;
http.createServer((req, res) => {
// Choose a CSP based on the query parameters
const isWorkaround = req.url.includes('workaround');
const CSP = isWorkaround ? WORKAROUND_CSP : BROKEN_CSP;
// Serve the embedded contents
if (req.url == PDF_PATH) {
res.end('<html><body><h1>I am an embedded page!</h1></body></html>');
// Serve the parent/root page contents
} else {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200, {'Content-Security-Policy': CSP});
// Build parent page HTML
const link = isWorkaround ?
"Now there is content, but this is with the workaround of adding 'self' to child-src. <a href='/'>Go back to broken CSP</a>" :
"There should be content shown below this link. There isn't. <a href='/?workaround'>Go to workaround CSP</a>";
res.end(`<html><body>
<h1>Page with CSP</h1>
<b>This page's content security policy:</b>
<pre>${CSP}</pre>
<br>
${link}
<br>
${OBJECT_TAG}
</body></html>`);
}
}).listen(PORT);
console.log(`Server running on localhost:${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment