From 25c169c4fc31225e6243606babf3b78af47a72ed Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Wed, 2 Dec 2026 20:45:33 -0800 Subject: [PATCH] fix(artifacts): allow same-site navigations, fit Mermaid, inset the focused view Why Live acceptance of the artifacts service found that a link from Hub, Tracker or Flags got 403 (same-site GET navigations were rejected), Mermaid rendered tiny, and the floating pill covered the top of the focused viewer (the cast and the video controls). A framed hostile form also turned the viewer frame into a Chrome error page; that needed an explanation and a test. What - csrf: a GET/HEAD top-level document navigation (Sec-Fetch-Mode navigate, Dest document) is allowed when Sec-Fetch-Site is same-site, as it already was for none. cross-site navigations, frame navigations, every non-GET and same-site or cross-site subresource requests are still refused. - Framed form POST: not a missing header. form-action 'none' is enforced and reported; the frame's error page is Chrome refusing the navigation under the app page's frame-src, and no request reaches the app. The e2e content host now serves the real contentHeaders, the e2e app listener logs requests, and a hostile-fixture spec asserts nothing reaches the app (POST, GET, popup). - The focused viewer starts below the pill (--ar-inset-top, published by the pill from its own measured bottom edge). The Mermaid viewer fits the frame (scale up to 3x natural, down as needed, held to the frame height unless it is already at natural size); the e2e content host serves the real viewer. Verification bunx turbo run build typecheck test lint --filter=@shepherdjerred/artifacts (454 unit tests, conformance allowlist unchanged); bun run test:e2e (desktop, mobile, webkit: 239 passed); root //#knip //#jscpd //#check-flag-usage //#check-directory-file-counts //#quality-ratchet; lefthook pre-commit. Not run: live deployment checks, PostgreSQL extended tier (no change to it). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011u9pQkmfQzZFyzPbpimoiT --- packages/artifacts/README.md | 12 ++ packages/artifacts/e2e/fake-content.ts | 112 +++++++------ packages/artifacts/e2e/fake-service.ts | 4 + packages/artifacts/e2e/focused-inset.spec.ts | 68 ++++++++ packages/artifacts/e2e/hostile-frame.spec.ts | 153 ++++++++++++++++++ packages/artifacts/e2e/shell.spec.ts | 7 +- packages/artifacts/e2e/start.ts | 25 +++ .../src/client/shell/floating-nav.tsx | 36 ++++- .../artifacts/src/client/styles/viewers.css | 7 +- packages/artifacts/src/domain/csrf.ts | 14 +- packages/artifacts/src/domain/domain.test.ts | 96 ++++++++++- packages/artifacts/src/domain/mermaid-fit.ts | 17 ++ packages/artifacts/src/server/assets.ts | 5 +- .../artifacts/src/viewer/mermaid-viewer.ts | 30 ++++ 14 files changed, 525 insertions(+), 61 deletions(-) create mode 100644 packages/artifacts/e2e/focused-inset.spec.ts create mode 100644 packages/artifacts/e2e/hostile-frame.spec.ts create mode 100644 packages/artifacts/src/domain/mermaid-fit.ts diff --git a/packages/artifacts/README.md b/packages/artifacts/README.md index f1cbad8dd7..e46d55fdcc 100644 --- a/packages/artifacts/README.md +++ b/packages/artifacts/README.md @@ -29,6 +29,18 @@ and framed with the same sandbox tokens, without `allow-same-origin`. A content URL carries a random 24-byte token minted at commit (`Version.contentToken`), and sources are scoped to that token's prefix. +The app host's CSRF rule (`src/domain/csrf.ts`) lets a top-level document +navigation by GET or HEAD arrive `same-origin`, `none` (a typed URL) or +`same-site` (a link from Hub or another console, which are same-site with this +host). Every other `same-site` or `cross-site` request is refused, including a +navigation from a sandboxed artifact (always `cross-site`) and any frame +navigation. A hostile artifact that submits a form at the app from inside the +viewer frame is stopped before a request is sent: the frame's own +`form-action 'none'` reports a violation, and the app page's `frame-src` (the +content origin only) refuses the navigation, which Chrome paints as an error +page in that frame. The e2e proves nothing reaches the app (`hostile-frame.spec.ts`); +the CSRF rule is the second line behind it. + Every request needs a `Tailscale-User-Login` in the `operatorLogins` configuration. There is no bearer token: agents and Jerred present the same login, so a token would authenticate nothing new. This deviates from Flags, diff --git a/packages/artifacts/e2e/fake-content.ts b/packages/artifacts/e2e/fake-content.ts index 7466f2ee54..e70e0a641e 100644 --- a/packages/artifacts/e2e/fake-content.ts +++ b/packages/artifacts/e2e/fake-content.ts @@ -4,11 +4,14 @@ * headers, injects the bridge into HTML and serves `Range` requests so video * seeking works. There is no tRPC and no cookie on this origin. */ +import { contentHeaders } from "#domain/csp.ts"; +import { normalizeArtifactPath, type ArtifactKind } from "#shared/contract.ts"; import { - ALLOWED_CDN_ORIGINS, - normalizeArtifactPath, -} from "#shared/contract.ts"; -import { buildBridge, type BridgeAssets } from "#server/assets.ts"; + buildBridge, + createViewerAssets, + mermaidViewerHtml, + type BridgeAssets, +} from "#server/assets.ts"; export type ContentFile = { readonly path: string; @@ -18,6 +21,7 @@ export type ContentFile = { }; export type ContentVersion = { + readonly kind: ArtifactKind; readonly entryPath: string; readonly files: ReadonlyMap; }; @@ -28,48 +32,25 @@ export type ContentSource = { readonly origins: () => { readonly app: string; readonly content: string }; }; +const VIEWER_PATH = /^\/_viewer\/([\w.-]+)$/u; const TOKEN_PATH = /^\/_t\/([\w-]+)\/(.*)$/u; -const CDN = ALLOWED_CDN_ORIGINS.join(" "); const ALLOW = "GET, HEAD, OPTIONS"; /** Types a browser may render inline; anything else is offered as a download. */ const INLINE_TYPE = /^(?:text\/|image\/|video\/|audio\/|font\/|application\/(?:pdf|json|javascript|xml|wasm|x-asciicast))/u; -/** The Content-Security-Policy of one token prefix, adapted so every source is an absolute origin plus path. */ -export function contentSecurityPolicy( - prefix: string, - origins: { readonly app: string; readonly content: string }, -): string { - return [ - "sandbox allow-scripts allow-forms allow-popups", - "default-src 'none'", - `img-src ${prefix} data:`, - `media-src ${prefix}`, - `style-src ${prefix} 'unsafe-inline' ${CDN}`, - `script-src ${prefix} ${origins.content}/_bridge/ 'unsafe-inline' ${CDN}`, - `font-src ${prefix} ${CDN}`, - `connect-src ${prefix}`, - "form-action 'none'", - "base-uri 'none'", - "frame-src 'none'", - `frame-ancestors ${origins.app}`, - ].join("; "); -} - +/** The real service's isolation headers, token-scoped: the e2e proves what ships. */ function baseHeaders( - prefix: string, + token: string | null, origins: { readonly app: string; readonly content: string }, ): Headers { - return new Headers({ - "Content-Security-Policy": contentSecurityPolicy(prefix, origins), - "Access-Control-Allow-Origin": "*", - "Cross-Origin-Resource-Policy": "cross-origin", - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "no-referrer", - "Access-Control-Expose-Headers": - "Content-Length, Content-Range, Accept-Ranges, ETag", - }); + return new Headers( + contentHeaders( + { appOrigin: origins.app, contentOrigin: origins.content }, + token, + ), + ); } function failure( @@ -150,7 +131,7 @@ async function serveBridge( request: Request, origins: { readonly app: string; readonly content: string }, ): Promise { - const headers = baseHeaders(`${origins.content}/_bridge/`, origins); + const headers = baseHeaders(null, origins); headers.set("Content-Type", "text/javascript; charset=utf-8"); headers.set("Cache-Control", "no-cache"); const bridge = await bridgeFor(origins.app); @@ -161,6 +142,44 @@ async function serveBridge( }); } +function isRead(request: Request): boolean { + return request.method === "GET" || request.method === "HEAD"; +} + +/** The real Mermaid viewer bundle, built on the first Mermaid artifact opened. */ +const viewer = createViewerAssets(); + +async function serveViewerAsset( + request: Request, + file: string, + origins: { readonly app: string; readonly content: string }, +): Promise { + const headers = baseHeaders(null, origins); + const asset = await viewer.get(file); + if (asset === undefined) return failure(404, "not found", headers); + headers.set("Content-Type", asset.contentType); + headers.set("Cache-Control", "private, max-age=31536000, immutable"); + return new Response(request.method === "HEAD" ? null : asset.bytes, { + headers, + }); +} + +/** What `/_t//` serves for a Mermaid artifact: the real viewer page. */ +async function serveMermaidViewer( + request: Request, + entryPath: string, + headers: Headers, +): Promise { + const html = mermaidViewerHtml({ + entryPath, + viewerScript: await viewer.mermaidEntry(), + bridgeSrc: "/_bridge/v1.js", + }); + headers.set("Content-Type", "text/html; charset=utf-8"); + headers.set("Cache-Control", "no-cache"); + return new Response(request.method === "HEAD" ? null : html, { headers }); +} + type FileResponse = { readonly request: Request; readonly file: ContentFile; @@ -222,19 +241,14 @@ export function createContentHandler( return (request) => { const url = new URL(request.url); const origins = source.origins(); - if ( - url.pathname === "/_bridge/v1.js" && - (request.method === "GET" || request.method === "HEAD") - ) + if (url.pathname === "/_bridge/v1.js" && isRead(request)) return serveBridge(request, origins); + const viewerFile = VIEWER_PATH.exec(url.pathname)?.[1]; + if (viewerFile !== undefined && isRead(request)) + return serveViewerAsset(request, viewerFile, origins); const match = TOKEN_PATH.exec(url.pathname); const token = match?.[1]; - const headers = baseHeaders( - token === undefined - ? `${origins.content}/_t/` - : `${origins.content}/_t/${token}/`, - origins, - ); + const headers = baseHeaders(token ?? null, origins); if (match === null || token === undefined) return failure(404, "not found", headers); if (request.method === "OPTIONS") { @@ -246,10 +260,12 @@ export function createContentHandler( headers.set("Access-Control-Max-Age", "86400"); return new Response(null, { status: 204, headers }); } - if (request.method !== "GET" && request.method !== "HEAD") + if (!isRead(request)) return failure(405, "method not allowed", headers, { Allow: ALLOW }); const version = source.resolveToken(token); if (version === null) return failure(404, "not found", headers); + if (version.kind === "mermaid" && match[2] === "") + return serveMermaidViewer(request, version.entryPath, headers); const path = resolvePath(match[2] ?? "", version.entryPath); const file = path === null ? undefined : version.files.get(path); const blob = file === undefined ? null : source.blob(file.sha256); diff --git a/packages/artifacts/e2e/fake-service.ts b/packages/artifacts/e2e/fake-service.ts index c3297d80b1..ea998e2d8e 100644 --- a/packages/artifacts/e2e/fake-service.ts +++ b/packages/artifacts/e2e/fake-service.ts @@ -227,7 +227,11 @@ export function createFakeService( const id = store.tokens.get(token); const version = id === undefined ? undefined : store.versions.get(id); if (version === undefined) return null; + const artifact = store.artifacts.get(version.artifactId); + if (artifact === undefined) + throw new Error(`version ${version.id} has no artifact`); return { + kind: artifact.kind, entryPath: version.entryPath, files: new Map(version.files.map((file) => [file.path, file])), }; diff --git a/packages/artifacts/e2e/focused-inset.spec.ts b/packages/artifacts/e2e/focused-inset.spec.ts new file mode 100644 index 0000000000..261c7d5ea7 --- /dev/null +++ b/packages/artifacts/e2e/focused-inset.spec.ts @@ -0,0 +1,68 @@ +/** + * The focused view starts below the floating pill, so no viewer renders under + * it, and the Mermaid viewer fills the frame's width. The canvas is unchanged: + * its frames pass under the pill on purpose. + */ +import { expect, test } from "@playwright/test"; +import { openFocused, resetAndSeed } from "./review-setup.ts"; +import type { SeededBoards } from "./seed.ts"; + +let seeded: SeededBoards; + +test.beforeAll(async ({ baseURL }) => { + test.setTimeout(120_000); + seeded = await resetAndSeed(baseURL); +}); + +const KINDS = ["htmlV2", "mermaid", "cast", "mp4", "png", "pdf"] as const; + +for (const kind of KINDS) { + test(`the ${kind} viewer starts below the pill`, async ({ page }) => { + await openFocused(page, seeded.demo[kind].artifactId); + const pill = await page.getByTestId("floating-nav").boundingBox(); + const pane = await page + .getByRole("region", { name: "Artifact" }) + .boundingBox(); + if (pill === null || pane === null) throw new Error("nothing to measure"); + expect(pane.y).toBeGreaterThanOrEqual(pill.y + pill.height); + }); +} + +test("a mermaid diagram is enlarged to fill its frame, within reason", async ({ + page, +}) => { + await openFocused(page, seeded.demo.mermaid.artifactId); + const svg = page + .frameLocator("[data-testid=artifact-frame]") + .locator("#diagram svg"); + await expect(svg).toBeVisible(); + const measured = await svg.evaluate((element) => { + const natural = + element instanceof SVGSVGElement ? element.viewBox.baseVal : null; + const box = element.getBoundingClientRect(); + return { + natural: natural?.width ?? 0, + width: box.width, + bottom: box.bottom, + room: document.body.clientWidth - 48, + height: window.innerHeight, + }; + }); + expect(measured.natural).toBeGreaterThan(0); + // Enlarged well past its natural size, but never past the cap or the frame. + expect(measured.width).toBeGreaterThan(measured.natural * 1.5); + expect(measured.width).toBeLessThanOrEqual(measured.natural * 3 + 1); + expect(measured.width).toBeLessThanOrEqual(measured.room + 1); + // This diagram is tall, so the frame's height is what limits it. + expect(measured.bottom).toBeLessThanOrEqual(measured.height - 24 + 1); +}); + +test("the canvas keeps its frames where they were", async ({ page }) => { + await page.goto("/b/demo?view=canvas"); + await expect(page.getByTestId("canvas-frame").first()).toBeVisible(); + // The pill publishes its reach for the focused view only: the canvas stays + // full-bleed from the top of the window and has no viewer pane to inset. + expect(await page.locator(".ar-viewer-pane").count()).toBe(0); + const canvas = await page.locator(".ar-cv").first().boundingBox(); + expect(canvas?.y).toBe(0); +}); diff --git a/packages/artifacts/e2e/hostile-frame.spec.ts b/packages/artifacts/e2e/hostile-frame.spec.ts new file mode 100644 index 0000000000..14d7817abd --- /dev/null +++ b/packages/artifacts/e2e/hostile-frame.spec.ts @@ -0,0 +1,153 @@ +/** + * A hostile artifact tries to reach the app from inside the viewer's frame. + * The page is published through the upload API like any other and framed by the + * real focused view; the app listener's request log (`e2e/start.ts`) then proves + * what reached the app. The log sits in front of every handler, so a request + * that is blocked in the browser never shows up in it. + */ +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { expect, test, type Page } from "@playwright/test"; +import { z } from "zod"; +import { resetAndSeed, sharedFixtures } from "./review-setup.ts"; +import { publishFixture } from "./seed.ts"; +import type { LoggedRequest } from "./start.ts"; + +const PROBE = "/api/_e2e/probe"; + +const LoggedRequestsSchema = z.array( + z.strictObject({ + method: z.string(), + path: z.string(), + site: z.string().nullable(), + mode: z.string().nullable(), + dest: z.string().nullable(), + }), +); + +function appUrl(baseURL: string | undefined): string { + if (baseURL === undefined) throw new Error("baseURL is not configured"); + return baseURL; +} + +async function requestLog(baseURL: string): Promise { + const response = await fetch(`${baseURL}/api/_e2e/requests`); + expect(response.status).toBe(200); + return LoggedRequestsSchema.parse(await response.json()); +} + +async function clearLog(baseURL: string): Promise { + const response = await fetch(`${baseURL}/api/_e2e/requests`, { + method: "DELETE", + }); + expect(response.status).toBe(204); +} + +/** Every route a hostile page can use to move itself or a popup onto the app. */ +function hostilePage(appOrigin: string): string { + return ` + +Hostile + +

Hostile fixture

+
+
+ + + +`; +} + +async function publishHostile(baseURL: string): Promise { + const { dir } = await sharedFixtures(); + const folder = path.join(dir, "hostile"); + await mkdir(folder, { recursive: true }); + const absPath = path.join(folder, "index.html"); + await writeFile(absPath, hostilePage(baseURL)); + const { artifactId } = await publishFixture(baseURL, { + board: "hostile", + title: "Hostile", + files: [{ path: "index.html", mediaType: "text/html", absPath }], + entryPath: "index.html", + }); + return artifactId; +} + +async function openHostile(page: Page, baseURL: string) { + const artifactId = await publishHostile(baseURL); + await page.goto(`/a/${artifactId}`); + const frame = page.frameLocator("[data-testid=artifact-frame]"); + await expect(frame.locator("#marker")).toBeVisible(); + return frame; +} + +/** Activates the frame the way a reviewer does, so its page takes clicks. */ +async function activate(page: Page): Promise { + await page.getByRole("button", { name: "Click to interact" }).click(); + await expect(page.getByTestId("artifact-frame")).toHaveJSProperty( + "inert", + false, + ); +} + +test.beforeEach(async ({ baseURL }) => { + await resetAndSeed(baseURL); + await clearLog(appUrl(baseURL)); +}); + +/** What reached the app listener at the probe path, as it logged it. */ +async function probeHits(baseURL: string): Promise { + const log = await requestLog(baseURL); + return log.filter((entry) => entry.path === PROBE); +} + +for (const [name, selector] of [ + ["POST form with no target", "#submit-post"], + ["GET form with no target", "#submit-get"], +] as const) { + test(`a framed ${name} never reaches the app`, async ({ + page, + baseURL, + browserName, + }) => { + const app = appUrl(baseURL); + const frame = await openHostile(page, app); + await activate(page); + const consoleLines: string[] = []; + page.on("console", (message) => { + consoleLines.push(message.text()); + }); + await clearLog(app); + await frame.locator(selector).click(); + // A blocked navigation settles at once; wait long enough for a sent one. + await page.waitForTimeout(1500); + expect(await probeHits(app)).toEqual([]); + // Whatever the frame shows now (Chromium paints an error page for a + // navigation its CSP checks refuse), it is never the app. + expect(page.frames().map((entry) => entry.url())).not.toContainEqual( + expect.stringContaining(PROBE), + ); + if (browserName === "chromium") + // form-action 'none' is what refuses it: reported by the frame's own policy. + expect(consoleLines.join("\n")).toContain("form-action 'none'"); + }); +} + +test("a framed form that opens a popup never reaches the app", async ({ + page, + baseURL, + context, +}) => { + const app = appUrl(baseURL); + const frame = await openHostile(page, app); + await activate(page); + await clearLog(app); + const popups: string[] = []; + context.on("page", (popup) => { + popups.push(popup.url()); + }); + await frame.locator("#submit-popup").click(); + await page.waitForTimeout(1500); + expect(await probeHits(app)).toEqual([]); + expect(popups.filter((url) => url.includes(PROBE))).toEqual([]); +}); diff --git a/packages/artifacts/e2e/shell.spec.ts b/packages/artifacts/e2e/shell.spec.ts index 1cbed5c979..b68a9d7a5e 100644 --- a/packages/artifacts/e2e/shell.spec.ts +++ b/packages/artifacts/e2e/shell.spec.ts @@ -229,7 +229,7 @@ test.describe("floating nav", () => { await expect(page.locator("header.ar-top")).toHaveCount(1); }); - test("the canvas is full-bleed: the viewer starts at the top of the page", async ({ + test("the canvas is full-bleed; the focused viewer starts below the pill", async ({ page, }) => { await page.goto("/b/concepts"); @@ -239,7 +239,10 @@ test.describe("floating nav", () => { const pane = await page .getByRole("region", { name: "Artifact" }) .boundingBox(); - expect(pane?.y).toBe(0); + const pill = await page.getByTestId("floating-nav").boundingBox(); + expect(pane?.y).toBeGreaterThanOrEqual( + (pill?.y ?? 0) + (pill?.height ?? 0), + ); }); test("the nav pill keeps the workspace switcher and Inbox, and the heading is the board title", async ({ diff --git a/packages/artifacts/e2e/start.ts b/packages/artifacts/e2e/start.ts index 0be2d28437..0d923545be 100644 --- a/packages/artifacts/e2e/start.ts +++ b/packages/artifacts/e2e/start.ts @@ -17,6 +17,15 @@ const PLACEHOLDER_INDEX = ` `; +/** One request the app listener received, as the app's own handler would see it. */ +export type LoggedRequest = { + readonly method: string; + readonly path: string; + readonly site: string | null; + readonly mode: string | null; + readonly dest: string | null; +}; + export type E2eServer = { readonly appOrigin: string; readonly contentOrigin: string; @@ -51,6 +60,7 @@ export function startE2eServer( options?: FakeServiceOptions, ): E2eServer { const service = createFakeService(options ?? { settleMs: 0 }); + const requests: LoggedRequest[] = []; const content = Bun.serve({ hostname: "127.0.0.1", port: 0, @@ -65,6 +75,21 @@ export function startE2eServer( const { pathname } = new URL(request.url); if (pathname === "/readyz" || pathname === "/healthz") return new Response("ok"); + // The request log: every other request that reaches the app listener is + // recorded before any handler runs, so a spec can prove a request never + // arrived. The log and its reset are the only routes that are not logged. + if (pathname === "/api/_e2e/requests") { + if (request.method !== "DELETE") return Response.json(requests); + requests.length = 0; + return new Response(null, { status: 204 }); + } + requests.push({ + method: request.method, + path: pathname, + site: request.headers.get("Sec-Fetch-Site"), + mode: request.headers.get("Sec-Fetch-Mode"), + dest: request.headers.get("Sec-Fetch-Dest"), + }); if (pathname.startsWith("/_")) return new Response("not found", { status: 404 }); const served = await service.appFetch(request); diff --git a/packages/artifacts/src/client/shell/floating-nav.tsx b/packages/artifacts/src/client/shell/floating-nav.tsx index 37af8cbdf6..a1ef8c7f01 100644 --- a/packages/artifacts/src/client/shell/floating-nav.tsx +++ b/packages/artifacts/src/client/shell/floating-nav.tsx @@ -2,6 +2,7 @@ import { Menu } from "@base-ui/react/menu"; import { AppSwitcher } from "@shepherdjerred/console-ui"; import { ThemeButton } from "@shepherdjerred/console-ui/components/shell/phone-nav.tsx"; import { KeyboardIcon, MoreHorizontalIcon } from "lucide-react"; +import { useLayoutEffect, useRef } from "react"; import { Link, useNavigate } from "react-router"; import { CURRENT_APP, SWITCHER_APPS } from "./app-nav.ts"; import { useShell } from "./shell-context.tsx"; @@ -15,6 +16,37 @@ export type NavMenuItem = { readonly onSelect?: () => void; }; +/** The gap kept between the pill's bottom edge and the content below it. */ +const NAV_GAP = 8; + +/** + * Publishes how far down the pill reaches as `--ar-inset-top` (its bottom edge + * plus a small gap), kept current as the pill wraps or resizes, so a page whose + * content must not sit under the pill (the focused view) can start below it. + * The canvas does not read it: its frames pass under the pill on purpose. + */ +function useNavInset(ref: React.RefObject): void { + useLayoutEffect(() => { + const element = ref.current; + if (element === null) return; + const root = document.documentElement; + const publish = (): void => { + const { bottom } = element.getBoundingClientRect(); + root.style.setProperty( + "--ar-inset-top", + `${String(Math.ceil(bottom + NAV_GAP))}px`, + ); + }; + publish(); + const observer = new ResizeObserver(publish); + observer.observe(element); + return () => { + observer.disconnect(); + root.style.removeProperty("--ar-inset-top"); + }; + }, [ref]); +} + /** * The shell's top bar and the page's own header as one floating pill at the * top left: the workspace switcher and Inbox the bar had, then the page's @@ -35,8 +67,10 @@ export function FloatingNav({ }): React.JSX.Element { const { openShortcuts } = useShell(); const navigate = useNavigate(); + const pill = useRef(null); + useNavInset(pill); return ( -
+