feat(files): open markdown, HTML, and PDF files outside the workspace (#9140)

Co-authored-by: Claude Code <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Code authored and GitHub committed 2026-09-01 19:31:55 -07:00
1 parent f2a914b858
commit f46a709ee4
26 files changed
+394 -89

No files matched your search

+6 -4
View File
@@ -44,7 +44,7 @@ const testLayer = Layer.mergeAll(
).pipe(Layer.provideMerge(NodeServices.layer));
describe("AssetAccess", () => {
it.effect("issues exact URLs for images and videos outside the workspace", () =>
it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -54,6 +54,8 @@ describe("AssetAccess", () => {
["screenshot.png", "image/png"],
["recording.mp4", "video/mp4"],
["recording.webm", "video/webm"],
["report.html", "text/html"],
["report.pdf", "application/pdf"],
] as const) {
const filePath = path.join(outside, name);
yield* fs.writeFileString(filePath, "media");
@@ -104,12 +106,12 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects non-media files, disguised targets, and directories", () =>
it.effect("rejects non-previewable files, disguised targets, and directories", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
for (const name of ["report.html", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
const filePath = path.join(root, name);
yield* fs.writeFileString(filePath, "not media");
const error = yield* issueAssetUrl({
@@ -118,7 +120,7 @@ describe("AssetAccess", () => {
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
}
const disguisedPath = path.join(root, "disguised.png");
yield* fs.symlink(path.join(root, "report.html"), disguisedPath);
yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
const disguisedError = yield* issueAssetUrl({
resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: disguisedPath },
}).pipe(Effect.flip);
+3 -3
View File
@@ -14,9 +14,9 @@ import {
AssetWorkspaceRootNormalizationError,
} from "@t3tools/contracts";
import {
hostPreviewMimeTypeFromExtension,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
mediaMimeTypeFromExtension,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
@@ -246,7 +246,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
if (!canonicalFile) {
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
}
if (mediaMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
const identity = yield* openMediaFile(canonicalFile).pipe(
@@ -598,7 +598,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
Effect.orElseSucceed(() => null),
);
if (canonicalFile !== claims.filePath) return null;
const mimeType = mediaMimeTypeFromExtension(path.extname(canonicalFile));
const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
if (!mimeType) return null;
const file = yield* openMediaFile(canonicalFile, claims).pipe(
Effect.tapError((cause) =>
+7 -9
View File
@@ -324,15 +324,13 @@ describe("assetResponseHeaders", () => {
"X-Content-Type-Options": "nosniff",
});
});
it("declares utf-8 for HTML assets so non-ASCII content renders correctly", () => {
expect(assetResponseHeaders("/workspace/page.html")).toHaveProperty(
"Content-Type",
"text/html; charset=utf-8",
);
expect(assetResponseHeaders("/workspace/PAGE.HTM")).toHaveProperty(
"Content-Type",
"text/html; charset=utf-8",
);
it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
expect(assetResponseHeaders(path)).toMatchObject({
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
});
}
});
it("downloads uploaded documents without executing their content", () => {
+8 -1
View File
@@ -51,6 +51,10 @@ const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
// HTML previews are agent output, not the app. The sandbox gives the document an
// opaque origin: scripts run, but same-origin cookies, storage, and API calls are
// out of reach. Relative sibling assets still load through their signed URLs.
const HTML_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-modals";
// Types a browser may render as a document if a proxy strips the disposition
// header. Downloads of these fall back to octet-stream.
@@ -105,7 +109,10 @@ export function assetResponseHeaders(
: inlineVideoMimeType !== undefined && isSafeInlineVideoMimeType(inlineVideoMimeType)
? { "Content-Type": inlineVideoMimeType }
: lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
? { "Content-Type": "text/html; charset=utf-8" }
? {
"Content-Type": "text/html; charset=utf-8",
"Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
}
: {}),
...(!options?.download && lowerPath.endsWith(".svg")
? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
@@ -1,3 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO.
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -73,6 +76,53 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("reads host files outside the workspace root by absolute path", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const outsideDir = yield* makeTempDir;
yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n");
const absolutePath = path.join(outsideDir, "cleanup-report.md");
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: absolutePath,
});
expect(result).toEqual({
relativePath: absolutePath,
contents: "# Report\n",
byteLength: 9,
truncated: false,
});
}),
);
it.effect("rejects a FIFO without blocking on open", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const outsideDir = yield* makeTempDir;
const fifoPath = path.join(outsideDir, "pipe");
yield* Effect.promise(
() =>
new Promise<void>((resolve, reject) =>
NodeChildProcess.execFile("mkfifo", [fifoPath], (error) =>
error ? reject(error) : resolve(),
),
),
);
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: fifoPath })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError);
}),
);
it.effect("rejects reads outside the workspace root", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -212,6 +262,22 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("rejects writes by absolute path", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
const outsideDir = yield* makeTempDir;
const absolutePath = path.join(outsideDir, "cleanup-report.md");
const error = yield* workspaceFileSystem
.writeFile({ cwd, relativePath: absolutePath, contents: "# Edited\n" })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
}),
);
it.effect("invalidates workspace entry search cache after writes", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
@@ -3,10 +3,13 @@
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
* Owns workspace-root-relative file read/write operations and their associated
* safety checks and cache invalidation hooks.
* safety checks and cache invalidation hooks. Reads also accept absolute host
* paths so clients can show files an agent left outside the workspace; writes
* never leave the root.
*
* @module WorkspaceFileSystem
*/
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import type {
@@ -104,7 +107,10 @@ export type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;
export class WorkspaceFileSystem extends Context.Service<
WorkspaceFileSystem,
{
/** Read a UTF-8 text file relative to the workspace root. */
/**
* Read a UTF-8 text file relative to the workspace root, or any host file by
* absolute path.
*/
readonly readFile: (
input: ProjectReadFileInput,
) => Effect.Effect<
@@ -132,9 +138,31 @@ export const make = Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
/**
* Resolves the file a read targets. Workspace-relative paths must stay inside the
* root, symlinks included. An absolute path reads a host file in place, such as a
* report an agent wrote to a temp directory; it gets no root check.
*/
const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* (
input: ProjectReadFileInput,
) {
const requestedPath = input.relativePath.trim();
if (path.isAbsolute(requestedPath)) {
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(requestedPath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: requestedPath,
operationPath: requestedPath,
operation: "realpath-target",
cause,
}),
});
return { relativePath: requestedPath, realTargetPath };
}
const target = yield* workspacePaths.resolveRelativePathWithinRoot({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -177,10 +205,24 @@ export const make = Effect.gen(function* () {
resolvedPath: realTargetPath,
});
}
return { relativePath: target.relativePath, realTargetPath };
});
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
const target = yield* resolveReadTarget(input);
const realTargetPath = target.realTargetPath;
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
// Non-blocking so a FIFO cannot hang the open; the stat below rejects
// it. Regular files ignore the flag. Windows lacks it.
try: () =>
NodeFSP.open(
realTargetPath,
NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NONBLOCK ?? 0),
),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,