Skip to content

Commit 914c439

Browse files
authored
Escape closing script tag when using define:vars (#7044)
1 parent c6b0a69 commit 914c439

File tree

4 files changed

+15
-3
lines changed

4 files changed

+15
-3
lines changed

.changeset/fresh-baboons-switch.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Escape closing script tag with `define:vars`

packages/astro/src/runtime/server/render/util.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export function defineScriptVars(vars: Record<any, any>) {
4343
for (const [key, value] of Object.entries(vars)) {
4444
// Use const instead of let as let global unsupported with Safari
4545
// https://stackoverflow.com/questions/29194024/cant-use-let-keyword-in-safari-javascript
46-
output += `const ${toIdent(key)} = ${JSON.stringify(value)};\n`;
46+
output += `const ${toIdent(key)} = ${JSON.stringify(value).replace(/<\/script>/g, "\\x3C/script>")};\n`;
4747
}
4848
return markHTMLString(output);
4949
}

packages/astro/test/astro-directives.test.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ describe('Directives', async () => {
1414
const html = await fixture.readFile('/define-vars/index.html');
1515
const $ = cheerio.load(html);
1616

17-
expect($('script')).to.have.lengthOf(3);
17+
expect($('script')).to.have.lengthOf(4);
1818

1919
let i = 0;
2020
for (const script of $('script').toArray()) {
@@ -24,9 +24,12 @@ describe('Directives', async () => {
2424
if (i < 2) {
2525
// Inline defined variables
2626
expect($(script).toString()).to.include('const foo = "bar"');
27-
} else {
27+
} else if (i < 3) {
2828
// Convert invalid keys to valid identifiers
2929
expect($(script).toString()).to.include('const dashCase = "bar"');
30+
} else {
31+
// Closing script tags in strings are escaped
32+
expect($(script).toString()).to.include('const bar = "<script>bar\\x3C/script>"');
3033
}
3134
i++;
3235
}

packages/astro/test/fixtures/astro-directives/src/pages/define-vars.astro

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import Title from "../components/Title.astro"
33
let foo = 'bar'
44
let bg = 'white'
55
let fg = 'black'
6+
let bar = '<script>bar</script>'
67
---
78

89
<html>
@@ -28,6 +29,9 @@ let fg = 'black'
2829
<script id="inline-3" define:vars={{ 'dash-case': foo }}>
2930
console.log(foo);
3031
</script>
32+
<script id="inline-4" define:vars={{ bar }}>
33+
console.log(bar);
34+
</script>
3135

3236
<Title />
3337
</body>

0 commit comments

Comments
 (0)