Skip to content

Commit

Permalink
Escape closing script tag when using define:vars (#7044)
Browse files Browse the repository at this point in the history
  • Loading branch information
Steffan153 authored May 15, 2023
1 parent c6b0a69 commit 914c439
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-baboons-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Escape closing script tag with `define:vars`
2 changes: 1 addition & 1 deletion packages/astro/src/runtime/server/render/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,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)};\n`;
output += `const ${toIdent(key)} = ${JSON.stringify(value).replace(/<\/script>/g, "\\x3C/script>")};\n`;
}
return markHTMLString(output);
}
Expand Down
7 changes: 5 additions & 2 deletions packages/astro/test/astro-directives.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('Directives', async () => {
const html = await fixture.readFile('/define-vars/index.html');
const $ = cheerio.load(html);

expect($('script')).to.have.lengthOf(3);
expect($('script')).to.have.lengthOf(4);

let i = 0;
for (const script of $('script').toArray()) {
Expand All @@ -24,9 +24,12 @@ describe('Directives', async () => {
if (i < 2) {
// Inline defined variables
expect($(script).toString()).to.include('const foo = "bar"');
} else {
} else if (i < 3) {
// Convert invalid keys to valid identifiers
expect($(script).toString()).to.include('const dashCase = "bar"');
} else {
// Closing script tags in strings are escaped
expect($(script).toString()).to.include('const bar = "<script>bar\\x3C/script>"');
}
i++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Title from "../components/Title.astro"
let foo = 'bar'
let bg = 'white'
let fg = 'black'
let bar = '<script>bar</script>'
---

<html>
Expand All @@ -28,6 +29,9 @@ let fg = 'black'
<script id="inline-3" define:vars={{ 'dash-case': foo }}>
console.log(foo);
</script>
<script id="inline-4" define:vars={{ bar }}>
console.log(bar);
</script>

<Title />
</body>
Expand Down

0 comments on commit 914c439

Please sign in to comment.