Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/consolidate-script-escaping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Improves handling of special characters in inline `<script>` content
11 changes: 11 additions & 0 deletions packages/astro/src/runtime/server/escape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import { streamAsyncIterator } from './util.js';
// Leverage the battle-tested `html-escaper` npm package.
export const escapeHTML = escape;

/**
* Serializes a value to a JSON string that is safe to embed inside a `<script>` tag.
* All `<` characters are escaped to `\u003c` so the browser's HTML parser cannot be
* tricked into closing the script block early via `</script>` variants (case-insensitive,
* whitespace, or self-closing forms) or `<!--` comment injection.
* @see https://mathiasbynens.be/notes/etago
*/
export function stringifyForScript(value: any): string {
return JSON.stringify(value)?.replace(/</g, '\\u003c');
}

export class HTMLBytes extends Uint8Array {}

// TypeScript won't let us define this in the class body so have to do it
Expand Down
23 changes: 5 additions & 18 deletions packages/astro/src/runtime/server/render/server-islands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { encryptString, generateCspDigest } from '../../../core/encryption.js';
import type { SSRResult } from '../../../types/public/internal.js';
import { markHTMLString } from '../escape.js';
import { markHTMLString, stringifyForScript } from '../escape.js';
import { renderChild } from './any.js';
import { createThinHead, type ThinHead } from './astro/head-and-content.js';
import type { RenderDestination } from './common.js';
Expand All @@ -18,20 +18,7 @@ export function containsServerDirective(props: Record<string | number, any>) {
return 'server:component-directive' in props;
}

const SCRIPT_RE = /<\/script/giu;
const COMMENT_RE = /<!--/gu;
const SCRIPT_REPLACER = '<\\/script';
const COMMENT_REPLACER = '\\u003C!--';

/**
* Encodes the script end-tag open (ETAGO) delimiter and opening HTML comment syntax for JSON inside a `<script>` tag.
* @see https://mathiasbynens.be/notes/etago
*/
function safeJsonStringify(obj: any) {
return JSON.stringify(obj)
.replace(SCRIPT_RE, SCRIPT_REPLACER)
.replace(COMMENT_RE, COMMENT_REPLACER);
}

function createSearchParams(
encryptedComponentExport: string,
Expand Down Expand Up @@ -214,17 +201,17 @@ export class ServerIslandComponent {

// Get adapter headers for inline script
const adapterHeaders = this.result.internalFetchHeaders || {};
const headersJson = safeJsonStringify(adapterHeaders);
const headersJson = stringifyForScript(adapterHeaders);

const method = useGETRequest
? // GET request
`const headers = new Headers(${headersJson});
let response = await fetch('${serverIslandUrl}', { headers });`
: // POST request
`let data = {
encryptedComponentExport: ${safeJsonStringify(componentExportEncrypted)},
encryptedProps: ${safeJsonStringify(propsEncrypted)},
encryptedSlots: ${safeJsonStringify(slotsEncrypted)},
encryptedComponentExport: ${stringifyForScript(componentExportEncrypted)},
encryptedProps: ${stringifyForScript(propsEncrypted)},
encryptedSlots: ${stringifyForScript(slotsEncrypted)},
};
const headers = new Headers({ 'Content-Type': 'application/json', ...${headersJson} });
let response = await fetch('${serverIslandUrl}', {
Expand Down
7 changes: 2 additions & 5 deletions packages/astro/src/runtime/server/render/util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { clsx } from 'clsx';
import type { SSRElement } from '../../../types/public/internal.js';
import { HTMLString, markHTMLString } from '../escape.js';
import { HTMLString, markHTMLString, stringifyForScript } from '../escape.js';
import { isPromise } from '../util.js';
import type { RenderDestination, RenderDestinationChunk, RenderFunction } from './common.js';

Expand Down Expand Up @@ -44,10 +44,7 @@ export function defineScriptVars(vars: Record<any, any>) {
for (const [key, value] of Object.entries(vars)) {
// Use const instead of let as let global unsupported with Safari
// https://stackoverflow.com/questions/29194024/cant-use-let-keyword-in-safari-javascript
output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
/<\/script>/g,
'\\x3C/script>',
)};\n`;
output += `const ${toIdent(key)} = ${stringifyForScript(value)};\n`;
}
return markHTMLString(output);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/test/astro-directives.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('Directives', async () => {
assert.equal($(script).toString().includes('const dashCase = "bar"'), true);
} else if (i < 4) {
// Closing script tags in strings are escaped
assert.equal($(script).toString().includes('const bar = "<script>bar\\x3C/script>"'), true);
assert.equal($(script).toString().includes('const bar = "\\u003cscript>bar\\u003c/script>"'), true);
} else {
// Vars with undefined values are handled
assert.equal($(script).toString().includes('const undef = undefined'), true);
Expand Down
26 changes: 25 additions & 1 deletion packages/astro/test/units/render/html-primitives.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,31 @@ describe('defineScriptVars', () => {
it('sanitizes </script> to prevent XSS injection', () => {
const result = String(defineScriptVars({ evil: '</script>' }));
assert.ok(!result.includes('</script>'), 'should not contain literal </script>');
assert.ok(result.includes('\\x3C/script>'), 'should escape the closing tag');
assert.ok(result.includes('\\u003c/script>'), 'should escape the closing tag');
});

it('sanitizes case-insensitive </script> variants', () => {
for (const tag of ['</Script>', '</SCRIPT>', '</sCrIpT>']) {
const result = String(defineScriptVars({ evil: tag }));
assert.ok(!result.includes(tag), `should not contain literal ${tag}`);
}
});

it('sanitizes </script> with trailing whitespace before >', () => {
for (const tag of ['</script >', '</script\t>', '</script\n>']) {
const result = String(defineScriptVars({ evil: tag }));
assert.ok(!result.includes(tag), `should not contain literal ${JSON.stringify(tag)}`);
}
});

it('sanitizes self-closing </script/>', () => {
const result = String(defineScriptVars({ evil: '</script/>' }));
assert.ok(!result.includes('</script/>'), 'should not contain literal </script/>');
});

it('handles undefined values without throwing', () => {
const result = String(defineScriptVars({ undef: undefined }));
assert.ok(result.includes('const undef = undefined;'));
});

it('converts keys with spaces to valid JS identifiers', () => {
Expand Down
Loading