Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
make-pdf: quotes in alt text, titles and raw HTML can no longer add script handlers (GST-3641) (#4761)
Garry Tan40986b7c76ff
diff --git a/changelog.d/make-pdf-quote-entities-stay-in-attributes.md b/changelog.d/make-pdf-quote-entities-stay-in-attributes.mdnew file mode 100644index 000000000..e3ee54bf6--- /dev/null+++ b/changelog.d/make-pdf-quote-entities-stay-in-attributes.md@@ -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.diff --git a/make-pdf/src/render.ts b/make-pdf/src/render.tsindex ac43415ae..19be20bed 100644--- a/make-pdf/src/render.ts+++ b/make-pdf/src/render.ts@@ -79,15 +79,11 @@ export function render(opts: RenderOptions): RenderResult {// 2. Sanitizeconst 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, "");-- // javascript: URLs in href/src/action/formaction+ // 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 (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;.*diff --git a/make-pdf/src/smartypants.ts b/make-pdf/src/smartypants.tsindex deee22295..62a537b6a 100644--- a/make-pdf/src/smartypants.ts+++ b/make-pdf/src/smartypants.ts@@ -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");diff --git a/make-pdf/test/render.test.ts b/make-pdf/test/render.test.tsindex 4fa9b7a0e..e95de526e 100644--- a/make-pdf/test/render.test.ts+++ b/make-pdf/test/render.test.ts@@ -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 dashconst 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", () => {