Search code examples
node.jskoakoa2

How to setup extra content-security-policy based on file type in koa?


The goal is to setup special rules for svg files,

server {
    add_header Content-Security-Policy "default-src 'none'; child-src https://www.youtube.com; font-src 'self' https://fonts.gstatic.com; frame-ancestors 'none'; frame-src https://www.youtube.com; img-src 'self'; media-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com";

    location ~ \.svg$ {
        add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'; style-src 'self' 'unsafe-inline'";
    }
}

for the 1st rule, we can do

ctx.response.set('Content-Security-Policy', 'default-src ...');

How about the 2nd line for the svg files.


Solution

  • Just use regular expression

    const svgPattern = /.+\.svg$/;
    if (filename.test(svgPattern)) {
      // add required header
    }