fix(core): improve island props serialization (#3071)

This commit is contained in:
Marvin Hagemeister
2025-06-30 16:31:58 +02:00
committed by GitHub
parent 8d3b8c53c6
commit 8416078b6a
5 changed files with 135 additions and 7 deletions
+7 -3
View File
@@ -32,6 +32,7 @@ import {
import { escape as escapeHtml } from "@std/html";
import { HttpError } from "../../error.ts";
import { getCodeFrame } from "../../dev/middlewares/error_overlay/code_frame.tsx";
import { escapeScript } from "../../utils.ts";
const enum OptionsType {
ATTR = "attr",
@@ -455,7 +456,9 @@ function FreshRuntimeScript() {
id={`__FRSH_STATE_${partialId}`}
type="application/json"
// deno-lint-ignore react-no-danger
dangerouslySetInnerHTML={{ __html: JSON.stringify(json) }}
dangerouslySetInnerHTML={{
__html: escapeScript(JSON.stringify(json), { json: true }),
}}
/>
);
} else {
@@ -476,8 +479,9 @@ function FreshRuntimeScript() {
.join(",") +
"}";
const serializedProps = JSON.stringify(
stringify(islandProps, stringifiers),
const serializedProps = escapeScript(
JSON.stringify(stringify(islandProps, stringifiers)),
{ json: true },
);
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
+13
View File
@@ -53,3 +53,16 @@ export function pathToExportName(filePath: string): string {
const regex = /^[^a-z_$]|[^a-z0-9_$]/gi;
return name.replaceAll(regex, "_").replaceAll(/_{2,}/g, "_");
}
const SCRIPT_ESCAPE = /<\/(style|script)/gi;
const COMMENT_ESCAPE = /<!--/gi;
// See https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
export function escapeScript(
content: string,
options: { json?: boolean } = {},
): string {
return content
.replaceAll(SCRIPT_ESCAPE, "<\\/$1")
.replaceAll(COMMENT_ESCAPE, options.json ? "\\u003C!--" : "\\x3C!--");
}
+42 -1
View File
@@ -1,5 +1,5 @@
import { expect } from "@std/expect";
import { mergePaths, pathToExportName } from "./utils.ts";
import { escapeScript, mergePaths, pathToExportName } from "./utils.ts";
Deno.test("mergePaths", () => {
expect(mergePaths("", "")).toEqual("");
@@ -20,3 +20,44 @@ Deno.test("filenameToExportName", () => {
"collapse_repeat_dash",
);
});
Deno.test("escapeScriptContent - closing </script> + </style>", () => {
expect(
escapeScript(
"foo</script>bar</style>baz</script>foobar",
),
).toEqual(
"foo<\\/script>bar<\\/style>baz<\\/script>foobar",
);
expect(
escapeScript(
"foo</ScRIpT>bar</StYLe>baz</SCRIPT>foobar",
),
).toEqual(
"foo<\\/ScRIpT>bar<\\/StYLe>baz<\\/SCRIPT>foobar",
);
});
Deno.test("escapeScript - legacy <!--", () => {
expect(escapeScript("<!--<script>")).toEqual("\\x3C!--<script>");
expect(escapeScript("<!--</script>")).toEqual("\\x3C!--<\\/script>");
});
Deno.test("escapeScript - script combined", () => {
expect(escapeScript(`// This is a comment containing <!--
let foo = x <!--y; // That's valid JS operators
const s = "This is a string containing <!--";`)).toEqual(
`// This is a comment containing \\x3C!--
let foo = x \\x3C!--y; // That's valid JS operators
const s = "This is a string containing \\x3C!--";`,
);
});
Deno.test("escapeScript - json", () => {
expect(escapeScript("<!--<script>", { json: true })).toEqual(
"\\u003C!--<script>",
);
expect(escapeScript("<!--</ScRIpt>", { json: true })).toEqual(
"\\u003C!--<\\/ScRIpt>",
);
});
+3 -2
View File
@@ -1,7 +1,7 @@
import { useEffect } from "preact/hooks";
import { useSignal } from "@preact/signals";
export function EscapeIsland(_props: { str: string }) {
export function EscapeIsland(props: { str: string }) {
const active = useSignal(false);
useEffect(() => {
@@ -10,7 +10,8 @@ export function EscapeIsland(_props: { str: string }) {
return (
<div class={active.value ? "ready" : ""}>
it works
<p>it works</p>
<div>{props.str}</div>
</div>
);
}
+70 -1
View File
@@ -31,6 +31,7 @@ import { getBuildCache } from "../src/app.ts";
import type { FreshConfig } from "../src/config.ts";
import { FreshAttrs } from "./fixtures_islands/FreshAttrs.tsx";
import { FakeServer } from "../src/test_utils.ts";
import { PARTIAL_SEARCH_PARAM } from "../src/constants.ts";
await buildProd(allIslandApp);
@@ -577,6 +578,20 @@ Deno.test({
<EscapeIsland str={`"foo"asdf`} />
</Doc>,
);
})
.get("/foo", (ctx) => {
return ctx.render(
<Doc>
<EscapeIsland str={`<script>alert('hey')</script>`} />
</Doc>,
);
})
.get("/bar", (ctx) => {
return ctx.render(
<Doc>
<EscapeIsland str={`<!--<script>alert('hey')</script>`} />
</Doc>,
);
});
await withBrowserApp(app, async (page, address) => {
@@ -585,9 +600,63 @@ Deno.test({
// Page would error here
const text = await page
.locator<HTMLDivElement>(".ready")
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
// Page would error here
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`"foo"asdf`);
});
// Check escaping of `</`
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo`, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`<script>alert('hey')</script>`);
});
// Check escaping of `<!--`
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/bar`, { waitUntil: "load" });
await page.locator(".ready").wait();
const text = await page
.locator<HTMLDivElement>(".ready p")
.evaluate((el) => el.textContent!);
expect(text).toEqual("it works");
const text2 = await page
.locator<HTMLDivElement>(".ready div")
.evaluate((el) => el.textContent!);
expect(text2).toEqual(`<!--<script>alert('hey')</script>`);
});
// Partials (they use a different code path)
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/foo?${PARTIAL_SEARCH_PARAM}`, {
waitUntil: "load",
});
const text = await page
.locator<HTMLScriptElement>("script[type='application/json']")
.evaluate((el) => el.textContent!);
const json = JSON.parse(text);
expect(json.props).toContain("<script>alert('hey')</script>");
});
},
});