mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-29 19:34:29 +01:00
make-pdf: quotes in alt text, titles and raw HTML can no longer add script handlers (GST-3641) (#4761)
Quotes in image alt text, link titles and raw HTML attributes now stay inside their attribute, so a Markdown file can no longer add an `onerror`, `onload` or `javascript:` link that runs in make-pdf's print browser. Why: the print browser runs page scripts, and on main a crafted image caption made it send the document's own text to another address. Nothing to do: ordinary Markdown prints the same (609 of gstack's own Markdown files render identically). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p2/red-team#1 reader=red-team
This commit is contained in:
1 parent
1cb381b048
commit
40986b7c76
4 files changed
+194
-31
No files matched your search
@@ -0,0 +1,4 @@
|
||||
---
|
||||
important: security
|
||||
---
|
||||
**make-pdf keeps quotes in alt text, link titles and raw HTML attributes inside the attribute, so a Markdown file can no longer add an `onerror`, `onload` or `javascript:` link that runs in the print browser.** make-pdf used to turn `"` back into `"` after its sanitizer had run, so an image caption holding a quote followed by an `onerror` handler printed as a live handler; quote entities are now read as quotes only in text, where they become curly quotes. The sanitizer also catches a handler or `javascript:` link written right after a `/` or a closing quote inside a raw HTML block, and no longer leaves an attribute or element open when it removes handler text. Handler-looking text such as `/onload=` is still removed wherever it appears, URLs and code included. Quotes in alt text and titles also render correctly now instead of cutting the text short.
|
||||
+23
-30
@@ -79,15 +79,11 @@ export function render(opts: RenderOptions): RenderResult {
|
||||
// 2. Sanitize
|
||||
const cleanHtml = sanitizeUntrustedHtml(directedHtml);
|
||||
|
||||
// 3. Decode common entities so smartypants can match raw " and '.
|
||||
// marked HTML-encodes quotes in text ("hello" → "hello");
|
||||
// without decoding, smartypants' regex never fires. These get re-encoded
|
||||
// implicitly by the browser's HTML parser downstream, and for the ones
|
||||
// that should stay as curly-quote Unicode, that IS the final form.
|
||||
const decoded = decodeTypographicEntities(cleanHtml);
|
||||
|
||||
// 4. Smartypants (code-safe)
|
||||
const typographicHtml = smartypants(decoded);
|
||||
// 3. Smartypants (code-safe). It reads marked's quote entities
|
||||
// (", ') in text as quotes and curls them; tags, code and URLs
|
||||
// keep theirs, so a decoded quote can never end an attribute value that
|
||||
// the sanitizer above has already checked.
|
||||
const typographicHtml = smartypants(cleanHtml);
|
||||
|
||||
// 4. Derive metadata (title from first H1 if not provided)
|
||||
const derivedTitle = opts.title ?? extractFirstHeading(typographicHtml) ?? "Document";
|
||||
@@ -174,19 +170,6 @@ export function render(opts: RenderOptions): RenderResult {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the HTML entities that marked emits for text-node quotes/apostrophes.
|
||||
* Only the four that matter for smartypants — leaves & alone because it
|
||||
* can be legitimately doubled (&amp;) and we don't want to double-decode.
|
||||
*/
|
||||
function decodeTypographicEntities(html: string): string {
|
||||
return html
|
||||
.replace(/"/g, "\"")
|
||||
.replace(/'/g, "'")
|
||||
.replace(/'/g, "'")
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// ─── Sanitizer ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -230,14 +213,24 @@ export function sanitizeUntrustedHtml(html: string): string {
|
||||
return `<svg${attrs}>${body.replace(/<script\b[\s\S]*?<\/script>/gi, "")}</svg>`;
|
||||
});
|
||||
|
||||
// Event handler attributes (on* in any case).
|
||||
s = s.replace(/\s+on[a-zA-Z]+\s*=\s*"[^"]*"/gi, "");
|
||||
s = s.replace(/\s+on[a-zA-Z]+\s*=\s*'[^']*'/gi, "");
|
||||
s = s.replace(/\s+on[a-zA-Z]+\s*=\s*[^\s>]+/gi, "");
|
||||
// Event handler attributes (on* in any case). The browser starts an
|
||||
// attribute name after whitespace, a "/" or a closing quote
|
||||
// (<img src="x"/onerror=…>, <img src="x"onerror=…>), so all four count.
|
||||
// An unquoted value stops at a quote or "<": marked writes a quote inside
|
||||
// an attribute as ", so the next straight quote closes the attribute
|
||||
// this handler text sits in, and the next "<" starts a tag (text such as
|
||||
// `a/onset=2` in a code span sits right before </code>). Eating either
|
||||
// would leave an attribute or element open. The value may be empty, so the
|
||||
// handler's name is always removed, even before a value that starts with
|
||||
// "<" (onerror=<!-- … runs its second line). Matching runs over the
|
||||
// whole page, text included, so "/on…=" inside a URL or code goes too.
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*"[^"]*"/gi, "");
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*'[^']*'/gi, "");
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*[^\s>"'`<]*/gi, "");
|
||||
|
||||
// javascript: URLs in href/src/action/formaction
|
||||
// javascript: URLs in href/src/action/formaction (same attribute starts).
|
||||
s = s.replace(
|
||||
/(\s(?:href|src|action|formaction|xlink:href)\s*=\s*)(?:"javascript:[^"]*"|'javascript:[^']*'|javascript:[^\s>]+)/gi,
|
||||
/([\s/"']\s*(?:href|src|action|formaction|xlink:href)\s*=\s*)(?:"javascript:[^"]*"|'javascript:[^']*'|javascript:[^\s>]+)/gi,
|
||||
'$1"#"',
|
||||
);
|
||||
|
||||
@@ -573,8 +566,8 @@ function extractFirstHeading(html: string): string | null {
|
||||
|
||||
/**
|
||||
* Decode HTML entities in plain text extracted from rendered HTML. Distinct
|
||||
* from decodeTypographicEntities (which runs on in-pipeline HTML and preserves
|
||||
* & because &amp; can be legitimate there). This runs on text destined
|
||||
* from smartypants, which reads only quote entities, only in text, and leaves
|
||||
* & alone because &amp; can be legitimate there. This runs on text destined
|
||||
* for <title>, cover, and TOC entries where & MUST become & or escapeHtml
|
||||
* produces &amp;.
|
||||
*
|
||||
|
||||
@@ -76,7 +76,14 @@ export function smartypants(html: string): string {
|
||||
* 5. Single quotes (open/close pairing — after apostrophes)
|
||||
*/
|
||||
function transformText(text: string): string {
|
||||
let s = text;
|
||||
// marked writes text quotes as entities. Read them as quotes here, in text
|
||||
// only: every quote below becomes a curly one, so none can come out as
|
||||
// attribute or tag syntax however a tag was split.
|
||||
let s = text
|
||||
.replace(/"/g, "\"")
|
||||
.replace(/'/g, "'")
|
||||
.replace(/'/g, "'")
|
||||
.replace(/'/g, "'");
|
||||
|
||||
// Ellipsis: three literal dots (with optional spaces) → …
|
||||
s = s.replace(/\.\s?\.\s?\./g, "\u2026");
|
||||
|
||||
@@ -89,6 +89,21 @@ describe("smartypants", () => {
|
||||
expect(out).toContain(`href="it's-a-test.html"`);
|
||||
});
|
||||
|
||||
test("curls quote entities in text and leaves them encoded inside tags", () => {
|
||||
const out = smartypants(`<p>She said "hi" and it's 'ok'.</p><img alt="a "b" c's">`);
|
||||
expect(out).toBe(`<p>She said \u201chi\u201d and it\u2019s \u2018ok\u2019.</p><img alt="a "b" c's">`);
|
||||
});
|
||||
|
||||
// A tag split differently than the browser splits it (a ">" inside a quoted
|
||||
// value) must not turn the entities after it into straight quotes: the
|
||||
// browser reads them as part of the attribute, where a straight quote would
|
||||
// end the value and start a live onerror attribute.
|
||||
test("never turns a quote entity into a straight quote", () => {
|
||||
const input = `<img a"b="c>"/onerror="alert(1)"/x='y'z'>`;
|
||||
const count = (s: string) => (s.match(/["']/g) ?? []).length;
|
||||
expect(count(smartypants(input))).toBe(count(input));
|
||||
});
|
||||
|
||||
test("does NOT convert -- in CLI flags", () => {
|
||||
// Prose like "try --verbose mode" should not turn -- into em dash
|
||||
const out = smartypants(`<p>Try --verbose mode.</p>`);
|
||||
@@ -190,6 +205,16 @@ describe("render (end-to-end)", () => {
|
||||
expect(result.meta.title).toBe("My Title");
|
||||
});
|
||||
|
||||
// Quote entities were decoded inside tags too, so alt="A "quoted"
|
||||
// caption" became alt="A "quoted" caption" and the attribute ended at "A ".
|
||||
test("keeps quotes inside image alt and link title attributes", () => {
|
||||
const md = `\n\nSee [the site](https://example.com 'The "best" site') and <abbr title="it's "x"">X</abbr>.\n`;
|
||||
const html = render({ markdown: md }).bodyHtml;
|
||||
expect(html).toContain(`alt="A "quoted" caption"`);
|
||||
expect(html).toContain(`title="The "best" site"`);
|
||||
expect(html).toContain(`<abbr title="it's "x"">X</abbr>`);
|
||||
});
|
||||
|
||||
test("uses --title override when provided", () => {
|
||||
const result = render({
|
||||
markdown: `# Auto-derived\n\nBody.`,
|
||||
@@ -321,6 +346,140 @@ describe("render (end-to-end)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ─── attribute injection ──────────────────────────────────────────────
|
||||
|
||||
/** Every attribute the browser's tokenizer would see, start tags only. */
|
||||
function browserAttrs(html: string): Array<{ tag: string; name: string; value: string }> {
|
||||
const out: Array<{ tag: string; name: string; value: string }> = [];
|
||||
let i = 0;
|
||||
while ((i = html.indexOf("<", i)) !== -1) {
|
||||
const open = /^<([a-zA-Z][^\s/>]*)/.exec(html.slice(i));
|
||||
if (!open) { i++; continue; }
|
||||
const tag = open[1]!.toLowerCase();
|
||||
i += open[0].length;
|
||||
while (i < html.length && html[i] !== ">") {
|
||||
if (/[\s/]/.test(html[i]!)) { i++; continue; }
|
||||
let name = html[i++]!;
|
||||
while (i < html.length && !/[\s/>=]/.test(html[i]!)) name += html[i++];
|
||||
while (/\s/.test(html[i] ?? "")) i++;
|
||||
let value = "";
|
||||
if (html[i] === "=") {
|
||||
i++;
|
||||
while (/\s/.test(html[i] ?? "")) i++;
|
||||
const q = html[i];
|
||||
if (q === '"' || q === "'") {
|
||||
const end = html.indexOf(q, i + 1);
|
||||
value = html.slice(i + 1, end < 0 ? html.length : end);
|
||||
i = end < 0 ? html.length : end + 1;
|
||||
} else {
|
||||
while (i < html.length && !/[\s>]/.test(html[i]!)) value += html[i++];
|
||||
}
|
||||
}
|
||||
out.push({ tag, name: name.toLowerCase(), value });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function decodeAttr(v: string): string {
|
||||
return v.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(quot|apos|amp));?/gi, (_m, hex, dec, named) =>
|
||||
hex ? String.fromCodePoint(parseInt(hex, 16))
|
||||
: dec ? String.fromCodePoint(parseInt(dec, 10))
|
||||
: ({ quot: '"', apos: "'", amp: "&" } as Record<string, string>)[named.toLowerCase()]!);
|
||||
}
|
||||
|
||||
function liveScript(html: string): string[] {
|
||||
return browserAttrs(html)
|
||||
.filter((a) => a.name.startsWith("on") ||
|
||||
(/^(?:href|src|xlink:href|action|formaction)$/.test(a.name) && /^\s*javascript:/i.test(decodeAttr(a.value))))
|
||||
.map((a) => `<${a.tag} ${a.name}=${a.value}>`);
|
||||
}
|
||||
|
||||
function attrsOf(html: string, tag: string): string[] {
|
||||
return browserAttrs(html).filter((a) => a.tag === tag).map((a) => a.name);
|
||||
}
|
||||
|
||||
describe("render() — quote entities never open attributes or tags", () => {
|
||||
test("an image alt cannot grow an onerror handler", () => {
|
||||
const html = render({ markdown: `\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(attrsOf(html, "img")).toEqual(["src", "alt"]);
|
||||
});
|
||||
|
||||
test("an image title cannot grow an onload handler or swallow the next paragraph", () => {
|
||||
const html = render({ markdown: `')\n\nAfter.\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(attrsOf(html, "img")).toEqual(["src", "alt", "title"]);
|
||||
expect(attrsOf(html, "p")).toEqual([]);
|
||||
expect(html).toContain("<p>After.</p>");
|
||||
expect(browserAttrs(html).find((a) => a.name === "title")!.value).not.toContain("<");
|
||||
});
|
||||
|
||||
test("a link title cannot grow a second href", () => {
|
||||
const html = render({ markdown: `[a](https://example.com 't" href="javascript:alert(1)')\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(attrsOf(html, "a")).toEqual(["href", "title"]);
|
||||
});
|
||||
|
||||
test("a raw-HTML title cannot become a javascript: href", () => {
|
||||
const html = render({ markdown: `<a title="x" href="javascript:alert(1)" y="">link</a>\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(attrsOf(html, "a")).toEqual(["title"]);
|
||||
});
|
||||
|
||||
test("single-quote entities in a raw-HTML attribute cannot end it", () => {
|
||||
for (const q of ["'", "'", "'"]) {
|
||||
const html = render({ markdown: `<abbr title='it${q}s/onmouseover=${q}alert(1)${q}'>X</abbr>\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(attrsOf(html, "abbr")).toEqual(["title"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("raw HTML blocks cannot start a handler or javascript: href after / or a closing quote", () => {
|
||||
const md = [
|
||||
"<div>",
|
||||
`<img src="pic.png"/onerror="alert(1)">`,
|
||||
`<img src="pic.png"onerror="alert(1)">`,
|
||||
`<img src='pic.png'onerror='alert(1)'>`,
|
||||
"<svg/onload=alert(1)></svg>",
|
||||
`<a title="t"href="javascript:alert(1)">j</a>`,
|
||||
`<a/href="javascript:alert(1)">k</a>`,
|
||||
"</div>",
|
||||
"",
|
||||
].join("\n");
|
||||
const html = render({ markdown: md }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(html).toContain(">j</a>");
|
||||
expect(html).toContain(">k</a>");
|
||||
});
|
||||
|
||||
// Handler removal runs over the whole page, so handler-looking text in a
|
||||
// code span is removed; it must stop before the closing </code> tag.
|
||||
test("removing handler-looking text never eats a tag", () => {
|
||||
const html = render({ markdown: "See `a/onset=2` and `b onset=3` here.\n" }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(html).toContain("<p>See <code>a/</code> and <code>b</code> here.</p>");
|
||||
});
|
||||
|
||||
// An unquoted value can't hold a space, but the parser decodes to a
|
||||
// line break, so onerror=<!-- code runs "code" after the comment.
|
||||
test("a handler whose unquoted value starts with < or a quote is still removed", () => {
|
||||
for (const value of ["<!--a", "<!-- document.title=1", "\"x", "'x", ""]) {
|
||||
const html = render({ markdown: `<div>\n<img src=pic.png onerror=${value}>\n</div>\n` }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
expect(html).not.toMatch(/onerror/i);
|
||||
}
|
||||
});
|
||||
|
||||
test("ordinary quotes still curl and ordinary attributes stay", () => {
|
||||
const html = render({ markdown: `She said "hi" -- it's fine. \n` }).bodyHtml;
|
||||
expect(html).toContain("\u201chi\u201d");
|
||||
expect(html).toContain("it\u2019s");
|
||||
expect(html).toContain(`title="A title"`);
|
||||
expect(attrsOf(html, "img")).toEqual(["src", "alt", "title"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── print-css ──────────────────────────────────────────────
|
||||
|
||||
describe("printCss", () => {
|
||||
|
||||
Reference in new issue
Block a user