Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/lib/readme.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ describe("parseBlocks", () => {
expect(p).toEqual({ kind: "text", segs: [{ text: "it's 'fine' ' <b>" }] });
});

it("leaves no markup behind in link text, even when tags are nested to dodge one pass", () => {
const [p] = parseBlocks(`<p><a href="${ISSUE}"><scr<b>ipt>alert(1)<b>y</b></a></p>`);
if (p.kind !== "text") throw new Error("expected text");
expect(p.segs).toHaveLength(1);
expect(p.segs[0].text).not.toMatch(/[<>]/);
expect(p.segs[0].text).toContain("alert(1)y");
});

it("survives references that name no real character", () => {
const [p] = parseBlocks("<p>a&#x110000;b&#xD800;c&#0;d&bogus;e</p>");
expect(p).toEqual({ kind: "text", segs: [{ text: "a\ufffdb\ufffdc\ufffdd&bogus;e" }] });
Expand Down
14 changes: 13 additions & 1 deletion src/lib/readme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,24 @@ function decode(s: string): string {
});
}

// Removes markup until none is left: one pass over "<scr<b>ipt>" would leave "<script>".
// The result is only ever rendered as text. Entities are decoded afterwards on purpose, so a
// README that writes "&lt;b&gt;" still shows the literal text "<b>".
function stripTags(html: string): string {
let out = html;
for (let prev = ""; prev !== out; ) {
prev = out;
out = out.replace(/<[^>]*>/g, "");
}
return out.replace(/[<>]/g, "");
}

function segments(html: string): Seg[] {
const segs: Seg[] = [];
const re = /<a\s+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>|<[^>]+>|([^<]+)/g;
for (const m of html.matchAll(re)) {
if (m[1] !== undefined) {
const text = decode(m[2].replace(/<[^>]+>/g, "")).trim();
const text = decode(stripTags(m[2])).trim();
const href = safeHref(m[1]);
if (text) segs.push(href ? { text, href } : { text });
} else if (m[3] !== undefined) {
Expand Down
Loading