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: Enable adapter-cloudflare to specify Content-Security-Policy in _headers file #13290

Closed
wants to merge 2 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
6 changes: 6 additions & 0 deletions .changeset/two-zebras-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@sveltejs/adapter-cloudflare': minor
'@sveltejs/kit': minor
---

Enable adapter-cloudflare to specify Content-Security-Policy in \_headers file
23 changes: 16 additions & 7 deletions packages/adapter-cloudflare/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export default function (options = {}) {
JSON.stringify(get_routes_json(builder, written_files, options.routes ?? {}), null, '\t')
);

writeFileSync(`${dest}/_headers`, generate_headers(builder.getAppPath()), { flag: 'a' });
writeFileSync(`${dest}/_headers`, generate_headers(builder), { flag: 'a' });

if (builder.prerendered.redirects.size > 0) {
writeFileSync(`${dest}/_redirects`, generate_redirects(builder.prerendered.redirects), {
Expand Down Expand Up @@ -159,18 +159,27 @@ function get_routes_json(builder, assets, { include = ['/*'], exclude = ['<all>'
};
}

/** @param {string} app_dir */
function generate_headers(app_dir) {
return `
# === START AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
/** @param {import('@sveltejs/kit').Builder} builder */
function generate_headers(builder) {
const app_dir = builder.getAppPath();
const csp_header = builder.generateCspHeaderValue();

let headers = '# === START AUTOGENERATED SVELTE IMMUTABLE HEADERS ===';

if (csp_header) {
headers += `\n/*\n Content-Security-Policy: ${csp_header}`;
}

headers += `
/${app_dir}/*
X-Robots-Tag: noindex
Cache-Control: no-cache
/${app_dir}/immutable/*
! Cache-Control
Cache-Control: public, immutable, max-age=31536000
# === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
`.trimEnd();
# === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===`;

return headers;
}

/** @param {Map<string, { status: number; location: string }>} redirects */
Expand Down
9 changes: 9 additions & 0 deletions packages/kit/src/core/adapt/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import generate_fallback from '../postbuild/fallback.js';
import { write } from '../sync/utils.js';
import { list_files } from '../utils.js';
import { find_server_assets } from '../generate_manifest/find_server_assets.js';
import { Csp } from '../../runtime/server/page/csp.js';

const pipe = promisify(pipeline);
const extensions = ['.html', '.js', '.mjs', '.json', '.css', '.svg', '.xml', '.wasm'];
Expand Down Expand Up @@ -192,6 +193,14 @@ export function create_builder({
});
},

generateCspHeaderValue() {
if (!config.kit.csp.directives) return null;

const csp = new Csp(config.kit.csp, { prerender: false });
Copy link
Member

@eltigerchino eltigerchino Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be generatePrerenderedCspHeaderValue() instead and prerender should be true? In the Cloudflare adapter case, it's primarily being used when serving prerendered pages.

When mode is 'auto', SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.

https://svelte.dev/docs/kit/configuration#csp

Also, I'm not sure if this would work. Don't we need to add the script and style sources before we generate the header?

csp.add_script(init_app);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think you're right, but I don't think it would matter as the CSP instance here will not be taking any script or style tags as input (unless prerendered pages are analyzed and their hashes are added to it).
Also on second thought the cloudflare _headers csp would need to allow unsafe-inline for script and style directives unless we do that analysis...
At that point I'm not sure if this PR is worth it 🤔

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll close this PR for now to keep the queue clean but let me know if you want me to re-open it.


return csp.csp_provider.get_header(false);
},

getBuildDirectory(name) {
return `${config.kit.outDir}/${name}`;
},
Expand Down
5 changes: 5 additions & 0 deletions packages/kit/src/exports/public.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ export interface Builder {
*/
generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string;

/**
* Generate a Content Security Policy header string which can be used to define static header files for adapters like adapter-cloudflare
*/
generateCspHeaderValue(): string | null;

/**
* Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`.
* @param name path to the file, relative to the build directory
Expand Down
5 changes: 5 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ declare module '@sveltejs/kit' {
*/
generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string;

/**
* Generate a Content Security Policy header string which can be used to define static header files for adapters like adapter-cloudflare
*/
generateCspHeaderValue(): string | null;

/**
* Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`.
* @param name path to the file, relative to the build directory
Expand Down
Loading