Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/artifacts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
112 changes: 64 additions & 48 deletions packages/artifacts/e2e/fake-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -18,6 +21,7 @@ export type ContentFile = {
};

export type ContentVersion = {
readonly kind: ArtifactKind;
readonly entryPath: string;
readonly files: ReadonlyMap<string, ContentFile>;
};
Expand All @@ -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(
Expand Down Expand Up @@ -150,7 +131,7 @@ async function serveBridge(
request: Request,
origins: { readonly app: string; readonly content: string },
): Promise<Response> {
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);
Expand All @@ -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<Response> {
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/<token>/` serves for a Mermaid artifact: the real viewer page. */
async function serveMermaidViewer(
request: Request,
entryPath: string,
headers: Headers,
): Promise<Response> {
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;
Expand Down Expand Up @@ -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") {
Expand All @@ -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);
Expand Down
4 changes: 4 additions & 0 deletions packages/artifacts/e2e/fake-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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])),
};
Expand Down
68 changes: 68 additions & 0 deletions packages/artifacts/e2e/focused-inset.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
Loading