Skip to content
Myr

Render a project's README as GitHub-flavoured Markdown, its links and images pointing into the repo at the SHA, sanitized

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- features/markdown/pipeline.ts holds the one plugin order (remark-gfm; rehype-raw, rehypeRepoUrls, rehype-sanitize with GitHub's defaultSchema plus `language-` on code, rehype-slug), because the order is the security property; react-markdown's defaultUrlTransform stays on as a second net. - features/markdown/resolve.ts: resolveRepoUrl is pure. `#…`, `""`, `//…` and any scheme stay as written; `/x` is repo-root, the rest is relative to dir with `..` clamped by the URL parser; query and hash kept; links to /<project>/blob/<sha>/…, media to /<project>/raw/<sha>/…, always the SHA. Only the parsed path is kept, so `/\host/x` stays inside the project. - Decision: a link ending in `/` goes to /tree/ (a folder), so it does not rely on the blob route redirecting. - Decision: `source[srcset]` is resolved to raw too (ky's and awesome's <picture> dark logos); the schema is unchanged. - RepoMarkdown: in-project `a` is a TanStack Link inside a router and a plain <a> outside one (views rendered alone, as their tests do); external links get rel="nofollow noopener noreferrer"; img gets lazy loading, async decoding and no referrer; prose prose-sm max-w-none dark:prose-invert. RepoMarkdownProps unchanged. - RepoText renders a non-Markdown README in a <pre>; isMarkdownPath tells the caller which to use (the props carry no path). - Tests: test/markdown-resolve.test.ts (each rule, `?raw=1#L3`, dir ""), test/markdown.test.tsx (script, onerror, javascript:/data:/vbscript: hrefs, iframe/style/form, user-content- name; relative image, ../../x, /LICENSE, external rel, #usage, raw-HTML img and picture srcset; GFM table, disabled task checkboxes, heading slug, code language; Link inside a router). - Bytes: nothing imports features/markdown yet, so the web build is unchanged (entry 717,922 of 1,665,000; JS 2,410,994 of 4,500,000); the pipeline alone is ~380 KB minified, ~116 KB gzip, which 904's import should add. - ASSUMPTION: a <style>'s CSS text left behind as inert text and double-prefixed footnote ids are acceptable GitHub-like defaults for W9 (noted for 999 in the issue).

authored by oscabriel · committed by oscabriel · parent 254268a · Browse files · 5 files+610 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+610 added−4 removed

  • tests:+298 added−0 removed
  • other:+312 added−4 removed

5 files+610 added−4 removed

modified:apps/web/src/features/markdown/markdown.tsx+114 added-4 removed
added:apps/web/src/features/markdown/pipeline.ts+119 added
1/**2 * The plugin chain that turns a project's Markdown into a safe tree, in3 * the one order that makes it safe (W9-D5). It is the security property4 * of the README renderer, so it lives here alone and is tested whole5 * (`test/markdown.test.tsx`):6 *7 * 1. `remarkGfm`: tables, task lists, strikethrough, autolinks, footnotes;8 * 2. `rehypeRaw`: the README's own HTML (`<p align="center"><img …>`)9 * becomes elements, so everything after sees it;10 * 3. `rehypeRepoUrls`: relative links and media point into the project at11 * the SHA (`resolve.ts`), before the sanitizer judges them;12 * 4. `rehypeSanitize` with `schema`: GitHub's allow-list, the last gate on13 * what comes in (no script, no handler, no `javascript:` or `data:`14 * URL, no iframe, style or form; a README's `id` and `name` prefixed15 * `user-content-`);16 * 5. `rehypeSlug`: heading ids, after the sanitizer, so `#usage` finds17 * `## Usage` unprefixed.18 *19 * react-markdown's `defaultUrlTransform` stays on as a second net.20 */21import { Predicate } from "effect";22import type { Element, Properties, Root } from "hast";23import type { Options } from "react-markdown";24import rehypeRaw from "rehype-raw";25import rehypeSanitize, { defaultSchema } from "rehype-sanitize";26import type { Options as Schema } from "rehype-sanitize";27import rehypeSlug from "rehype-slug";28import remarkGfm from "remark-gfm";29import { visit } from "unist-util-visit";3031import { resolveRepoUrl } from "./resolve.ts";32import type { RepoUrlContext } from "./resolve.ts";3334/** A list of unified plugins, each with its options, as react-markdown takes them. */35export type PluggableList = NonNullable<Options["rehypePlugins"]>;3637/** Where a Markdown file was read: the project, the commit, and the file's directory (`""` is the root). */38export type MarkdownAt = Omit<RepoUrlContext, "kind">;3940/**41 * GitHub's allow-list (`hast-util-sanitize`'s `defaultSchema`), with a42 * code block's `language-…` class kept on `code`, and nothing else added.43 */44export const schema: Schema = {45 ...defaultSchema,46 attributes: {47 ...defaultSchema.attributes,48 code: [49 ...(defaultSchema.attributes?.code ?? []),50 ["className", /^language-./u],51 ],52 },53};5455/** Elements whose URL loads bytes into the page: they read the raw file. */56const media = new Set(["img", "source", "video"]);5758/** One `srcset` candidate (`url [descriptor]`), its URL resolved. */59const candidate = (value: string, at: RepoUrlContext) => {60 const [url = "", ...descriptor] = value.trim().split(/\s+/u);6162 return [resolveRepoUrl(url, at), ...descriptor].join(" ");63};6465/** Rewrite one URL property, when the element carries it as a string. */66const rewrite = (67 properties: Properties,68 key: "href" | "src" | "srcSet",69 to: (value: string) => string70) => {71 const value = properties[key];7273 if (Predicate.isString(value)) {74 properties[key] = to(value);75 }76};7778const resolveElement = (node: Element, at: MarkdownAt) => {79 if (node.tagName === "a") {80 rewrite(node.properties, "href", (href) =>81 resolveRepoUrl(href, { ...at, kind: "link" })82 );83 }8485 if (!media.has(node.tagName)) {86 return;87 }8889 const here = { ...at, kind: "media" } as const;9091 rewrite(node.properties, "src", (src) => resolveRepoUrl(src, here));92 // rehype-raw keeps `srcset` as written: one string, candidates split by commas.93 rewrite(node.properties, "srcSet", (srcSet) =>94 srcSet95 .split(",")96 .map((value) => candidate(value, here))97 .join(", ")98 );99};100101/**102 * A rehype plugin: every `a[href]` and every `img`, `video` and `source`103 * `src` (and `srcset`) resolved into the project at the SHA.104 */105export const rehypeRepoUrls = (at: MarkdownAt) => (tree: Root) => {106 visit(tree, "element", (node) => {107 resolveElement(node, at);108 });109};110111export const remarkPlugins: PluggableList = [remarkGfm];112113/** The rehype half of the chain for one file, in its fixed order. */114export const rehypePluginsFor = (at: MarkdownAt): PluggableList => [115 rehypeRaw,116 [rehypeRepoUrls, at],117 [rehypeSanitize, schema],118 rehypeSlug,119];
added:apps/web/src/features/markdown/resolve.ts+79 added
added:apps/web/test/markdown-resolve.test.ts+80 added
added:apps/web/test/markdown.test.tsx+218 added
1/**2 * A project's Markdown file, rendered to HTML with `react-dom/server`, as3 * the Worker renders it: GitHub-flavoured Markdown and the README's own4 * HTML, its links and images pointing into the project at the commit it5 * was read at, and nothing that could run script or post a form.6 */7import { describe, expect, it } from "@effect/vitest";8import { CommitSha, ProjectName } from "@repo/protocol/ids";9import {10 RouterContextProvider,11 createMemoryHistory,12 createRootRoute,13 createRouter,14} from "@tanstack/react-router";15import type { ReactElement } from "react";16import { renderToString } from "react-dom/server";1718import {19 RepoMarkdown,20 RepoText,21 isMarkdownPath,22} from "../src/features/markdown/markdown.tsx";2324const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");2526const project = ProjectName.make("p");2728/** The file `<dir>/README.md` at `sha`, rendered with no router around it, as a view's test renders it. */29const rendered = (source: string, dir = "") =>30 renderToString(31 <RepoMarkdown at={sha} dir={dir} project={project} source={source} />32 );3334/** The same, inside a router, as the app renders it. */35const routed = (element: ReactElement) =>36 renderToString(37 <RouterContextProvider38 router={createRouter({39 history: createMemoryHistory({ initialEntries: ["/p"] }),40 routeTree: createRootRoute(),41 })}42 >43 {element}44 </RouterContextProvider>45 );4647/** Each `<a …>` opening tag in `markup`. */48const anchorsOf = (markup: string) => markup.match(/<a\b[^>]*>/gu) ?? [];4950describe("what a README cannot carry", () => {51 it("drops a script and what it says", () => {52 const markup = rendered("before\n\n<script>alert(1)</script>\n\nafter");5354 expect(markup).not.toContain("script");55 expect(markup).not.toContain("alert");56 expect(markup).toContain("<p>after</p>");57 });5859 it("keeps an image but not its event handler", () => {60 const markup = rendered("<img src=x onerror=alert(1)>");6162 expect(markup).toContain(`src="/p/raw/${sha}/x"`);63 expect(markup).not.toContain("onerror");64 expect(markup).not.toContain("alert");65 });6667 it.each([68 ["a javascript: link", "[x](javascript:alert(1))"],69 ["a data: link", '<a href="data:text/html,<b>hi</b>">x</a>'],70 ["a vbscript: link", "[x](vbscript:msgbox(1))"],71 ])("renders %s with no href", (_, source) => {72 const markup = rendered(source);7374 expect(anchorsOf(markup)).toStrictEqual(["<a>"]);75 expect(markup).not.toMatch(/javascript|data:|vbscript/u);76 });7778 it.each([79 ["an iframe", '<iframe src="https://e.org"></iframe>', "iframe"],80 ["a style", "<style>body{display:none}</style>", "<style"],81 ["a form", '<form action="/x"><input name="q"></form>', "action"],82 ])("drops %s", (_, source, word) => {83 const markup = rendered(`${source}\n\nafter`);8485 expect(markup).not.toContain(word);86 expect(markup).toContain("<p>after</p>");87 });8889 it("prefixes a name the README sets, so it cannot clobber the page's own", () => {90 const markup = rendered('<a name="top">Top</a>');9192 expect(markup).toMatch(/(?:id|name)="user-content-top"/u);93 });94});9596/** `docs/README.md`, rendered. */97const readme = (source: string) => rendered(source, "docs");9899describe("links and images in docs/README.md", () => {100 it("loads a relative image raw from the README's folder, at the SHA", () => {101 const markup = readme("![logo](./img/logo.png)");102103 expect(markup).toContain(`src="/p/raw/${sha}/docs/img/logo.png"`);104 expect(markup).toContain('loading="lazy"');105 expect(markup).toContain('decoding="async"');106 expect(markup).toContain('referrerPolicy="no-referrer"');107 });108109 it.each([110 ["[a](../../x)", `/p/blob/${sha}/x`],111 ["[b](/LICENSE)", `/p/blob/${sha}/LICENSE`],112 ["[g](guide.md#install)", `/p/blob/${sha}/docs/guide.md#install`],113 ])("opens %s inside the project", (source, href) => {114 expect(anchorsOf(readme(source))).toStrictEqual([`<a href="${href}">`]);115 });116117 it("opens a link inside the project through the router when there is one", () => {118 const markup = routed(119 <RepoMarkdown120 at={sha}121 dir="docs"122 project={project}123 source="[a](../../x?raw=1#L3)"124 />125 );126127 expect(anchorsOf(markup)).toStrictEqual([128 `<a href="/p/blob/${sha}/x?raw=1#L3">`,129 ]);130 });131132 it("leaves an external link as written, opened with no referrer", () => {133 const [anchor] = anchorsOf(readme("[c](https://e.org)"));134135 expect(anchor).toContain('href="https://e.org"');136 expect(anchor).toMatch(/rel="[^"]*\bnoopener\b[^"]*"/u);137 expect(anchor).toMatch(/rel="[^"]*\bnofollow\b[^"]*"/u);138 expect(anchor).toMatch(/rel="[^"]*\bnoreferrer\b[^"]*"/u);139 });140141 it("leaves a link to a heading as written", () => {142 expect(anchorsOf(readme("[d](#usage)"))).toStrictEqual([143 '<a href="#usage">',144 ]);145 });146147 it("resolves an image in the README's own HTML, as ky's and awesome's are written", () => {148 const markup = rendered(149 '<p align="center"><img src="media/logo.svg" width="200" alt="logo"></p>'150 );151152 expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);153 expect(markup).toContain('align="center"');154 });155156 it("resolves a picture's sources too, so the dark logo loads", () => {157 const markup = rendered(158 '<picture><source media="(prefers-color-scheme: dark)" srcset="media/dark.svg 1x, media/dark@2x.svg 2x"><img src="media/logo.svg"></picture>'159 );160161 expect(markup).toContain(162 `srcSet="/p/raw/${sha}/media/dark.svg 1x, /p/raw/${sha}/media/dark@2x.svg 2x"`163 );164 expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);165 });166});167168describe("GitHub-flavoured Markdown", () => {169 it("renders a table", () => {170 const markup = rendered("| a | b |\n| - | - |\n| 1 | 2 |");171172 expect(markup).toContain("<table>");173 expect(markup).toContain("<td>1</td>");174 });175176 it("renders a task list with checkboxes nobody can tick", () => {177 const markup = rendered("- [x] done\n- [ ] not yet");178179 expect(markup.match(/<input[^>]*>/gu)).toStrictEqual([180 '<input type="checkbox" disabled="" checked=""/>',181 '<input type="checkbox" disabled=""/>',182 ]);183 });184185 it("gives a heading an id a link can point at", () => {186 expect(rendered("## Hello World")).toContain('<h2 id="hello-world">');187 });188189 it("keeps a code block's language and draws it in mono", () => {190 const markup = rendered("```ts\nconst a = 1;\n```");191192 expect(markup).toContain('class="language-ts"');193 expect(markup).toContain("<pre");194 });195196 it("styles the whole as prose", () => {197 expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);198 });199});200201describe("a README that is not Markdown", () => {202 it.each([203 ["README.md", true],204 ["docs/readme.markdown", true],205 ["README.mdown", true],206 ["README", false],207 ["README.txt", false],208 ["README.rst", false],209 ])("reads %s as Markdown: %s", (path, markdown) => {210 expect(isMarkdownPath(path)).toBe(markdown);211 });212213 it("shows as written, in a pre", () => {214 const markup = renderToString(<RepoText source={"# not a heading\n<b>"} />);215216 expect(markup).toMatch(/^<pre[^>]*># not a heading\n&lt;b&gt;<\/pre>$/u);217 });218});