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

%sveltekit.nonce% is not replaced in content inserted in %sveltekit.head% #11882

Closed
ollema opened this issue Feb 22, 2024 · 1 comment
Closed

Comments

@ollema
Copy link

ollema commented Feb 22, 2024

Describe the bug

Background

Some svelte packages, such as mode-watcher, leverages <svelte:head> to insert for example a flash of unstyled content (FOUC) prevention snippet, something along the lines of:

<svelte:head>
	{@html '<script nonce="%sveltekit.nonce%">(' + setInitialMode.toString() + ')();</script>'}
</svelte:head>

That seems to work well for preventing FOUC - however the %sveltekit.nonce% is not replaced!

I noticed this when investigating svecosystem/mode-watcher#47 (comment)

Current behaviour

<svelte:head>
	{@html '<script nonce="%sveltekit.nonce%">console.log('hello')</script>'}
</svelte:head>

results in something like:

<!-- HEAD_svelte-cpyj77_START -->
<!-- HTML_TAG_START -->
<script nonce="%sveltekit.nonce%">console.log('hello')</script>
<!-- HTML_TAG_END -->
<!-- HEAD_svelte-cpyj77_END -->

Expected behaviour

<svelte:head>
	{@html '<script nonce="%sveltekit.nonce%">console.log('hello')</script>'}
</svelte:head>

should result in something like:

<!-- HEAD_svelte-cpyj77_START -->
<!-- HTML_TAG_START -->
<script nonce="6Ca/ONqXWMQvg4qhyLKJ0w==">console.log('hello')</script>
<!-- HTML_TAG_END -->
<!-- HEAD_svelte-cpyj77_END -->

Additional notes

The reason I believe that this is how it should work is because of how write_server.js is written.

There, we can see that first the head is replaced, then the nonce(s) are replaced. To further investigate this, I tried to modify the write_server.js code that is shipped in node_modules (not the source code linked above mind you):

from:

const server_template = ({
	config,
	hooks,
	has_service_worker,
	runtime_directory,
	template,
	error_page
}) => `
import root from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}';
import { set_building } from '__sveltekit/environment';
import { set_assets } from '__sveltekit/paths';
import { set_private_env, set_public_env } from '${runtime_directory}/shared-server.js';

export const options = {
	app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
	csp: ${s(config.kit.csp)},
	csrf_check_origin: ${s(config.kit.csrf.checkOrigin)},
	track_server_fetches: ${s(config.kit.dangerZone.trackServerFetches)},
	embedded: ${config.kit.embedded},
	env_public_prefix: '${config.kit.env.publicPrefix}',
	env_private_prefix: '${config.kit.env.privatePrefix}',
	hooks: null, // added lazily, via \`get_hooks\`
	preload_strategy: ${s(config.kit.output.preloadStrategy)},
	root,
	service_worker: ${has_service_worker},
	templates: {
		app: ({ head, body, assets, nonce, env }) => ${s(template)
			.replace('%sveltekit.head%', '" + head + "')
			.replace('%sveltekit.body%', '" + body + "')
			.replace(/%sveltekit\.assets%/g, '" + assets + "')
			.replace(/%sveltekit\.nonce%/g, '" + nonce + "')
			.replace(
				/%sveltekit\.env\.([^%]+)%/g,
				(_match, capture) => `" + (env[${s(capture)}] ?? "") + "`
			)},
		error: ({ status, message }) => ${s(error_page)
			.replace(/%sveltekit\.status%/g, '" + status + "')
			.replace(/%sveltekit\.error\.message%/g, '" + message + "')}
	},
	version_hash: ${s(hash(config.kit.version.name))}
};

export function get_hooks() {
	return ${hooks ? `import(${s(hooks)})` : '{}'};
}

export { set_assets, set_building, set_private_env, set_public_env };
`;

to:

const server_template = ({
	config,
	hooks,
	has_service_worker,
	runtime_directory,
	template,
	error_page
}) => `
import root from '../root.${isSvelte5Plus() ? 'js' : 'svelte'}';
import { set_building } from '__sveltekit/environment';
import { set_assets } from '__sveltekit/paths';
import { set_private_env, set_public_env } from '${runtime_directory}/shared-server.js';

export const options = {
	app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
	csp: ${s(config.kit.csp)},
	csrf_check_origin: ${s(config.kit.csrf.checkOrigin)},
	track_server_fetches: ${s(config.kit.dangerZone.trackServerFetches)},
	embedded: ${config.kit.embedded},
	env_public_prefix: '${config.kit.env.publicPrefix}',
	env_private_prefix: '${config.kit.env.privatePrefix}',
	hooks: null, // added lazily, via \`get_hooks\`
	preload_strategy: ${s(config.kit.output.preloadStrategy)},
	root,
	service_worker: ${has_service_worker},
	templates: {
		app: ({ head, body, assets, nonce, env }) => {
		// this works, nonce is replaced!
		console.log(head.replace(/%sveltekit\.nonce%/g, nonce));

		// this does not work, nonce is not replaced :(
		console.log(${s(template)
 			.replace('%sveltekit.head%', '" + head + "')
			.replace(/%sveltekit\.nonce%/g, '" + nonce + "')
		});

		return ${s(template)
			.replace('%sveltekit.head%', '" + head + "')
			.replace('%sveltekit.body%', '" + body + "')
			.replace(/%sveltekit\.assets%/g, '" + assets + "')
			.replace(/%sveltekit\.nonce%/g, '" + nonce + "')
			.replace(
				/%sveltekit\.env\.([^%]+)%/g,
				(_match, capture) => `" + (env[${s(capture)}] ?? "") + "`
			)}
    },
		error: ({ status, message }) => ${s(error_page)
			.replace(/%sveltekit\.status%/g, '" + status + "')
			.replace(/%sveltekit\.error\.message%/g, '" + message + "')}
	},
	version_hash: ${s(hash(config.kit.version.name))}
};

export function get_hooks() {
	return ${hooks ? `import(${s(hooks)})` : '{}'};
}

export { set_assets, set_building, set_private_env, set_public_env };
`;

In other words, I tried to log some stuff in the app templates section.

There, as indicated by the comments:

console.log(head.replace(/%sveltekit\.nonce%/g, nonce));

works and correctly replaces the nonce but:

console.log(s(template)
  .replace('%sveltekit.head%', '" + head + "')
  .replace(/%sveltekit\.nonce%/g, '" + nonce + "')
);

does not work. I am not sure why! Does it have something to do with the s(template) function? 🤔

Reproduction

https://stackblitz.com/github/svecosystem/mode-watcher-reproduction

open developer tools, notice how %sveltekit.nonce% is present and not replaced

System Info

System:
    OS: macOS 13.6.4
    CPU: (10) arm64 Apple M1 Pro
    Memory: 566.05 MB / 32.00 GB
    Shell: 3.6.4 - /run/current-system/sw/bin/fish
  Binaries:
    Node: 21.5.0 - /etc/profiles/per-user/s0001325/bin/node
    npm: 10.2.4 - /etc/profiles/per-user/s0001325/bin/npm
    pnpm: 8.15.1 - ~/Library/pnpm/pnpm
  Browsers:
    Chrome: 121.0.6167.184
    Safari: 17.3
  npmPackages:
    @sveltejs/adapter-node: ^4.0.1 => 4.0.1 
    @sveltejs/adapter-static: ^3.0.1 => 3.0.1 
    @sveltejs/kit: ^2.5.0 => 2.5.0 
    @sveltejs/vite-plugin-svelte: ^3.0.2 => 3.0.2 
    svelte: ^4.2.11 => 4.2.11 
    vite: ^5.1.3 => 5.1.3

Severity

serious, but I can work around it

@ollema
Copy link
Author

ollema commented Feb 22, 2024

@ollema ollema closed this as completed Feb 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant