[next] Sanitize <py-script> content + deprecate html content (#1663)

This commit is contained in:
Andrea Giammarchi
2023-08-31 10:43:28 +02:00
committed by GitHub
parent 0f2deeb71a
commit 74cd7c840a
5 changed files with 35 additions and 6 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,7 @@
import "@ungap/with-resolvers";
import { $ } from "basic-devtools";
import { define, XWorker } from "polyscript";
import { htmlDecode } from "./utils.js";
// this is imported as string (via rollup)
import display from "./display.py";
@@ -54,7 +55,7 @@ const after = () => {
* It either throws an error if the 'src' can't be fetched or it returns a fallback
* content as source.
*/
const fetchSource = async (tag, io) => {
const fetchSource = async (tag, io, asText) => {
if (tag.hasAttribute("src")) {
try {
return await fetch(tag.getAttribute("src")).then(getText);
@@ -62,7 +63,15 @@ const fetchSource = async (tag, io) => {
io.stderr(error);
}
}
return tag.textContent;
if (asText) return tag.textContent;
console.warn(
'Deprecated: use <script type="py"> for an always safe content parsing:\n',
tag.innerHTML,
);
return htmlDecode(tag.innerHTML);
};
// common life-cycle handlers for any node
@@ -211,7 +220,7 @@ define("py", {
defineProperty(element, "target", { value: show });
pyodide[`run${isAsync ? "Async" : ""}`](
await fetchSource(element, pyodide.io),
await fetchSource(element, pyodide.io, true),
);
} else {
// resolve PyScriptElement to allow connectedCallback
@@ -231,8 +240,8 @@ class PyScriptElement extends HTMLElement {
if (!this.executed) {
this.executed = true;
const { io, run } = await this._pyodide.promise;
this.srcCode = await fetchSource(this, io);
this.textContent = "";
this.srcCode = await fetchSource(this, io, !this.childElementCount);
this.replaceChildren();
run(this.srcCode);
this.style.display = "block";
}

View File

@@ -0,0 +1,6 @@
const entity = { "<": "&lt;", ">": "&gt;" };
const escape = (str) => str.replace(/[<>]/g, (key) => entity[key]);
export const htmlDecode = (html) =>
new DOMParser().parseFromString(escape(html), "text/html").documentElement
.textContent;

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="../core.css" />
<script type="module" src="../core.js"></script>
</head>
<body>
<body>
<py-script>import js; js.console.log(1<2, 1>2)</py-script>
<py-script>js.console.log("<div></div>")</py-script>
</body>
</body>
</html>

1
pyscript.core/types/utils.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
export function htmlDecode(html: any): string;