Skip to content
Myr

Merge branch 'build/905-readme-markdown'

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

authored by oscabriel · committed by oscabriel · parents 06e2229, 75d65f7 · Browse files · 5 files+630 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+630 added−4 removed

  • tests:+315 added−0 removed
  • other:+315 added−4 removed

5 files+630 added−4 removed

modified:apps/web/src/features/markdown/markdown.tsx+117 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+235 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 at `location`, as the app renders it. */35const routed = (element: ReactElement, location = "/p") =>36 renderToString(37 <RouterContextProvider38 router={createRouter({39 history: createMemoryHistory({ initialEntries: [location] }),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("marks a link to the page it is on as the current page, its query and fragment read as such", () => {133 const markup = routed(134 <RepoMarkdown135 at={sha}136 dir="docs"137 project={project}138 source="[a](../../x?raw=1#L3)"139 />,140 `/p/blob/${sha}/x?raw=1#L3`141 );142143 const [anchor] = anchorsOf(markup);144145 expect(anchor).toContain(`href="/p/blob/${sha}/x?raw=1#L3"`);146 expect(anchor).toContain('aria-current="page"');147 });148149 it("leaves an external link as written, opened with no referrer", () => {150 const [anchor] = anchorsOf(readme("[c](https://e.org)"));151152 expect(anchor).toContain('href="https://e.org"');153 expect(anchor).toMatch(/rel="[^"]*\bnoopener\b[^"]*"/u);154 expect(anchor).toMatch(/rel="[^"]*\bnofollow\b[^"]*"/u);155 expect(anchor).toMatch(/rel="[^"]*\bnoreferrer\b[^"]*"/u);156 });157158 it("leaves a link to a heading as written", () => {159 expect(anchorsOf(readme("[d](#usage)"))).toStrictEqual([160 '<a href="#usage">',161 ]);162 });163164 it("resolves an image in the README's own HTML, as ky's and awesome's are written", () => {165 const markup = rendered(166 '<p align="center"><img src="media/logo.svg" width="200" alt="logo"></p>'167 );168169 expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);170 expect(markup).toContain('align="center"');171 });172173 it("resolves a picture's sources too, so the dark logo loads", () => {174 const markup = rendered(175 '<picture><source media="(prefers-color-scheme: dark)" srcset="media/dark.svg 1x, media/dark@2x.svg 2x"><img src="media/logo.svg"></picture>'176 );177178 expect(markup).toContain(179 `srcSet="/p/raw/${sha}/media/dark.svg 1x, /p/raw/${sha}/media/dark@2x.svg 2x"`180 );181 expect(markup).toContain(`src="/p/raw/${sha}/media/logo.svg"`);182 });183});184185describe("GitHub-flavoured Markdown", () => {186 it("renders a table", () => {187 const markup = rendered("| a | b |\n| - | - |\n| 1 | 2 |");188189 expect(markup).toContain("<table>");190 expect(markup).toContain("<td>1</td>");191 });192193 it("renders a task list with checkboxes nobody can tick", () => {194 const markup = rendered("- [x] done\n- [ ] not yet");195196 expect(markup.match(/<input[^>]*>/gu)).toStrictEqual([197 '<input type="checkbox" disabled="" checked=""/>',198 '<input type="checkbox" disabled=""/>',199 ]);200 });201202 it("gives a heading an id a link can point at", () => {203 expect(rendered("## Hello World")).toContain('<h2 id="hello-world">');204 });205206 it("keeps a code block's language and draws it in mono", () => {207 const markup = rendered("```ts\nconst a = 1;\n```");208209 expect(markup).toContain('class="language-ts"');210 expect(markup).toContain("<pre");211 });212213 it("styles the whole as prose", () => {214 expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);215 });216});217218describe("a README that is not Markdown", () => {219 it.each([220 ["README.md", true],221 ["docs/readme.markdown", true],222 ["README.mdown", true],223 ["README", false],224 ["README.txt", false],225 ["README.rst", false],226 ])("reads %s as Markdown: %s", (path, markdown) => {227 expect(isMarkdownPath(path)).toBe(markdown);228 });229230 it("shows as written, in a pre", () => {231 const markup = renderToString(<RepoText source={"# not a heading\n<b>"} />);232233 expect(markup).toMatch(/^<pre[^>]*># not a heading\n&lt;b&gt;<\/pre>$/u);234 });235});