fix(python): load package description images only when asked (#6616)

* fix(python): load package description images only when asked, and list the PyPI link once

* fix(python): hold back image inputs and backgrounds too, and match the PyPI page by name

---------

Co-authored-by: LU XIANGRUI <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаLU XIANGRUI authored and GitHub committed 2026-12-01 21:22:13 +08:00
1 джерело fa0be07436
коміт a9e92d0665
8 files changed
+125 -7

No files matched your search

+12 -2
Переглянути файл
@@ -60,9 +60,13 @@ const SIX = {
summary: "Python 2 and 3 compatibility utilities",
latest: "1.17.0",
versions: ["1.17.0", "1.16.0"],
description: "# Six\n\nRead the [documentation](https://six.readthedocs.io/).<script>alert(1)</script>",
description:
"# Six\n\n![build](https://img.shields.io/six.svg)\n\nRead the [documentation](https://six.readthedocs.io/).<script>alert(1)</script>",
markdown: true,
links: [{ label: "Source", url: "https://github.com/benjaminp/six" }],
links: [
{ label: "Download", url: "https://pypi.org/project/six" },
{ label: "Source", url: "https://github.com/benjaminp/six" },
],
};
function open(interpreter = "") {
@@ -190,6 +194,12 @@ describe("Python Packages", () => {
fireEvent.click(screen.getByRole("link", { name: "PyPI" }));
fireEvent.click(screen.getByRole("link", { name: "documentation" }));
expect(mocks.openUrl.mock.calls).toEqual([["https://pypi.org/project/six/"], ["https://six.readthedocs.io/"]]);
// Images load from their sites only when asked for.
const doc = screen.getByRole("document", { name: "Package description" });
expect(doc.querySelector("img")).toBeNull();
expect(doc).toHaveTextContent("build");
fireEvent.click(screen.getByRole("button", { name: "Load Images" }));
expect(doc.querySelector("img")).toHaveAttribute("src", "https://img.shields.io/six.svg");
});
it("shows a description that is not Markdown as text", async () => {
+21 -3
Переглянути файл
@@ -40,6 +40,8 @@ import {
requirementOf,
rowKey,
vcsRequirement,
withoutMedia,
isPypiPage,
type Row,
} from "./model";
import styles from "./PythonPackages.module.css";
@@ -704,11 +706,17 @@ function openLink(e: MouseEvent) {
void openExternalUrl(a.getAttribute("href") ?? "");
}
/** The project's links and its description from PyPI: rendered when Markdown, else as text. */
/**
* The project's links and its description from PyPI: rendered when Markdown, else as text. Its
* images come from other sites (badges, GitHub), so they load only when asked for.
*/
function Docs({ found }: { found: PypiPackage }) {
const tx = useTx();
const [media, setMedia] = useState(false);
const html = useMarkupHtml({ kind: "markdown", value: found.markdown ? found.description : "" });
const links = [{ label: "PyPI", url: `https://pypi.org/project/${found.name}/` }, ...found.links];
const shown = useMemo(() => (media ? { html, count: 0 } : withoutMedia(html)), [media, html]);
const pypi = `https://pypi.org/project/${found.name}/`;
const links = [{ label: "PyPI", url: pypi }, ...found.links.filter((l) => !isPypiPage(l.url, found.name))];
return (
<>
<nav className={styles.links} aria-label={tx("Project links")} onClick={openLink}>
@@ -718,6 +726,16 @@ function Docs({ found }: { found: PypiPackage }) {
</a>
))}
</nav>
{shown.count > 0 && (
<div className={styles.note}>
<span>
<T>Images in the description load from other sites.</T>
</span>{" "}
<Button size="small" variant="ghost" onClick={() => setMedia(true)}>
<T>Load Images</T>
</Button>
</div>
)}
{found.description.trim() &&
(found.markdown ? (
<div
@@ -725,7 +743,7 @@ function Docs({ found }: { found: PypiPackage }) {
role="document"
aria-label={tx("Package description")}
onClick={openLink}
dangerouslySetInnerHTML={{ __html: html }}
dangerouslySetInnerHTML={{ __html: shown.html }}
/>
) : (
<pre className={styles.plainDoc} aria-label={tx("Package description")}>
+43
Переглянути файл
@@ -9,6 +9,8 @@ import {
diskRequirement,
isArchive,
isVcsUrl,
withoutMedia,
isPypiPage,
} from "./model";
const INSTALLED = [
@@ -130,3 +132,44 @@ describe("install from version control or disk", () => {
expect(isArchive(" dist/demo-1.0-py3-none-any.whl ")).toBe(true);
});
});
describe("withoutMedia", () => {
it("takes out what would load from other sites, keeping an image's alt text", () => {
const { html, count } = withoutMedia(
'<p><img src="https://img.shields.io/b.svg" alt="build"> ok</p><picture><source srcset="https://x/a.png"><img src="https://x/b.png"></picture><video src="https://x/v.mp4"></video>',
);
expect(html).toBe("<p>build ok</p>");
expect(count).toBe(3);
expect(withoutMedia("<p>text</p>")).toEqual({ html: "<p>text</p>", count: 0 });
});
it("holds back what the sanitizer lets through: image inputs and background attributes", async () => {
const { markdownToSafeHtml } = await import("@/editor/lsp/markdownParser");
const safe = markdownToSafeHtml(
'<input type="image" src="https://t/x.png"><table><tr><td background="https://t/y.png">c</td></tr></table>',
);
expect(safe).toContain("https://t/");
const { html, count } = withoutMedia(safe);
expect(html).not.toContain("https://t/");
expect(count).toBe(2);
});
});
describe("isPypiPage", () => {
it("knows a project's PyPI page however it is spelled", () => {
for (const url of [
"https://pypi.org/project/zope.interface/",
"http://pypi.org/project/zope-interface",
"https://www.pypi.org/project/Zope_Interface/",
])
expect(isPypiPage(url, "zope.interface")).toBe(true);
for (const url of [
"https://pypi.org/project/zope.interface/#files",
"https://pypi.org/project/zope.interface/1.0/",
"https://pypi.org/project/zope.schema/",
"https://github.com/zopefoundation/zope.interface",
"not a url",
])
expect(isPypiPage(url, "zope.interface")).toBe(false);
});
});
+43
Переглянути файл
@@ -86,3 +86,46 @@ export function diskRequirement(path: string) {
/** A wheel or source archive, which pip can install but not in editable mode. */
export const isArchive = (path: string) => /\.(whl|zip|tar\.gz|tgz|tar\.bz2|tar\.xz)$/i.test(path.trim());
/**
* `html` with its images, videos and audio taken out, and any other element's `src`-like
* attributes, so nothing loads from other sites: an image becomes its alt text. `count` is how
* many there were.
*/
export function withoutMedia(html: string): { html: string; count: number } {
const template = document.createElement("template");
template.innerHTML = html;
let count = 0;
for (const el of template.content.querySelectorAll("img, video, audio, source, picture")) {
if (el.localName === "picture") el.replaceWith(...el.childNodes);
else if (el.localName === "source") el.remove();
else {
count++;
el.replaceWith(el.getAttribute("alt") ?? "");
}
}
// Anything else that would fetch: `<input type="image" src>`, `<td background>`.
for (const el of template.content.querySelectorAll("[src], [srcset], [background], [poster]")) {
count++;
for (const name of ["src", "srcset", "background", "poster"]) el.removeAttribute(name);
}
return { html: template.innerHTML, count };
}
/** Whether `url` is the PyPI page of project `name`, however it is spelled (scheme, slash, PEP 503). */
export function isPypiPage(url: string, name: string) {
let u: URL;
try {
u = new URL(url);
} catch {
return false;
}
const project = /^\/project\/([^/]+)\/?$/.exec(u.pathname)?.[1];
return (
/^(www\.)?pypi\.org$/i.test(u.hostname) &&
!u.search &&
!u.hash &&
!!project &&
normalize(decodeURIComponent(project)) === normalize(name)
);
}