fix(chat): harden media preview handling

This commit is contained in:
Gabriel De Andrade committed 2026-07-29 23:29:22 -04:00
1 parent 54456158be
commit 292b685509
10 files changed
+404 -50

No files matched your search

+30 -4
View File
@@ -15,6 +15,14 @@ import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
async function readStream(stream: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-asset-access-test-",
});
@@ -122,10 +130,23 @@ describe("AssetAccess", () => {
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const token = suffix.slice(0, suffix.indexOf("/"));
expect(yield* resolveAsset(token, "browser-recording-demo.webm")).toEqual({
kind: "file",
const resolved = yield* resolveAsset(token, "browser-recording-demo.webm");
expect(resolved).toMatchObject({
kind: "open-file",
path: canonicalArtifactPath,
});
if (!resolved || resolved.kind !== "open-file") return;
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-open-artifact-outside-",
});
const secretPath = path.join(outsideDir, "secret.webm");
yield* fileSystem.writeFileString(secretPath, "secret-bytes");
yield* fileSystem.remove(artifactPath);
yield* fileSystem.symlink(secretPath, artifactPath);
expect(
Buffer.from(yield* Effect.promise(() => readStream(resolved.stream))).toString("utf8"),
).toBe("webm-bytes");
// Non-media files and traversal-style names are not issuable.
const nonMedia = yield* issueAssetUrl({
@@ -328,10 +349,15 @@ describe("AssetAccess", () => {
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "tool-output.png")).toEqual({
kind: "file",
const resolved = yield* resolveAsset(token, "tool-output.png");
expect(resolved).toMatchObject({
kind: "open-file",
path: canonicalImagePath,
});
if (!resolved || resolved.kind !== "open-file") return;
expect(Array.from(yield* Effect.promise(() => readStream(resolved.stream)))).toEqual([
137, 80, 78, 71,
]);
expect(yield* resolveAsset(token, "other.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
+63 -5
View File
@@ -1,3 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import type * as NodeFS from "node:fs";
import type { AssetResource } from "@t3tools/contracts";
import {
AssetAttachmentNotFoundError,
@@ -24,8 +27,10 @@ import {
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
WORKSPACE_VIDEO_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -42,6 +47,7 @@ import {
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { openReadableFileNoFollow } from "../noFollowFile.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -109,7 +115,20 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| {
readonly kind: "open-file";
readonly path: string;
readonly stream: NodeFS.ReadStream;
readonly size: number;
};
class ResolvedAssetOpenError extends Data.TaggedError("ResolvedAssetOpenError")<{
readonly path: string;
readonly resource: string;
readonly cause: unknown;
}> {}
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -162,6 +181,37 @@ const statIsFile = (path: string) =>
Effect.orElseSucceed(() => false),
);
const openResolvedAssetForRequest = Effect.fn("AssetAccess.openResolvedAssetForRequest")(
function* (input: { readonly path: string; readonly resource: string }) {
const platform = yield* HostProcessPlatform;
const opened = yield* Effect.tryPromise({
try: () => openReadableFileNoFollow(input.path, platform),
catch: (cause) =>
new ResolvedAssetOpenError({
path: input.path,
resource: input.resource,
cause,
}),
});
return {
kind: "open-file",
path: input.path,
...opened,
} satisfies ResolvedAsset;
},
(effect, input) =>
effect.pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to safely open resolved asset.", {
path: input.path,
resource: input.resource,
cause,
}),
),
Effect.orElseSucceed(() => null),
),
);
/**
* Resolve a browser artifact to its canonical path, rejecting anything that
* escapes the artifacts directory. Names are validated before and after
@@ -549,10 +599,15 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
if (claims.kind === "browser-artifact") {
// Re-resolved on every request: a signed token must not keep serving a
// path that was replaced by a symlink after issuance.
// Re-resolve and keep the validated descriptor open for the response so
// serving the asset cannot follow a path swapped after this check.
const artifactPath = yield* resolveCanonicalBrowserArtifact(claims.fileName);
return artifactPath ? ({ kind: "file", path: artifactPath } satisfies ResolvedAsset) : null;
return artifactPath
? yield* openResolvedAssetForRequest({
path: artifactPath,
resource: "browser artifact",
})
: null;
}
if (claims.kind === "thread-image") {
@@ -584,7 +639,10 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
Effect.orElseSucceed(() => Option.none()),
);
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: canonicalPath.value } satisfies ResolvedAsset)
? yield* openResolvedAssetForRequest({
path: canonicalPath.value,
resource: "thread image",
})
: null;
}
+13 -4
View File
@@ -270,12 +270,21 @@ export const assetRouteLayer = HttpRouter.add(
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const assetHeaders = {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
};
if (asset.kind === "open-file") {
return HttpServerResponse.raw(asset.stream, {
status: 200,
contentLength: asset.size,
contentType: Mime.getType(asset.path) ?? "application/octet-stream",
headers: assetHeaders,
});
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
headers: assetHeaders,
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
+1 -1
View File
@@ -172,8 +172,8 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
Stream.run(Sink.last()),
Effect.flatMap(Effect.fromOption),
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideContext(snapshotHandlerContext),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.matchCauseEffect({
onFailure: previewSnapshotFailure,
onSuccess: ({ encodedResult }) => {
@@ -2,6 +2,7 @@
import * as NodeCrypto from "node:crypto";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -19,8 +20,10 @@ import type {
PreviewTabId,
} from "@t3tools/contracts";
import { PreviewAutomationScreenshotSaveError } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../../../config.ts";
import { openWritableFileNoFollow } from "../../../noFollowFile.ts";
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
@@ -86,6 +89,40 @@ const writeScreenshotFile = (input: {
);
});
class ScreenshotFileWriteError extends Data.TaggedError("ScreenshotFileWriteError")<{
readonly path: string;
readonly cause: unknown;
}> {}
const writeScreenshotFileNoFollow = Effect.fn("PreviewToolkit.writeScreenshotFileNoFollow")(
function* (input: { readonly absolutePath: string; readonly screenshotBase64: string }) {
const platform = yield* HostProcessPlatform;
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => openWritableFileNoFollow(input.absolutePath, platform),
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
(handle) =>
Effect.tryPromise({
try: async () => {
const info = await handle.stat();
if (!info.isFile()) {
throw new Error(`Expected a regular screenshot destination: ${input.absolutePath}`);
}
await handle.truncate(0);
await handle.writeFile(Buffer.from(input.screenshotBase64, "base64"));
},
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
);
},
);
const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScreenshotArtifact")(
function* (input: {
readonly scope: McpInvocationContext.McpInvocationScope;
@@ -204,9 +241,9 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot"
return yield* fail("workspace-containment-validation");
}
// Refuse to write through a destination that is itself a symlink: the
// write would follow it, and a dangling link (realPath reports NotFound)
// could silently create a file outside the workspace at its target.
// Report a stable validation stage for links already present at the final
// destination. The descriptor-based write below also refuses path
// components swapped to symlinks after this check.
const destination = path.join(canonicalParent, path.basename(resolved.absolutePath));
const destinationIsSymlink = yield* fileSystem.readLink(destination).pipe(
Effect.as(true),
@@ -216,7 +253,7 @@ const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot"
return yield* fail("destination-symlink-validation");
}
yield* writeScreenshotFile({
yield* writeScreenshotFileNoFollow({
absolutePath: destination,
screenshotBase64: input.screenshotBase64,
}).pipe(Effect.mapError((cause) => fail("screenshot-write", cause)));
+140
View File
@@ -0,0 +1,140 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import type * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
// Node does not expose Darwin's all-components no-follow flag.
const DARWIN_O_NOFOLLOW_ANY = 0x20000000;
function errnoCode(cause: unknown): string | undefined {
return cause instanceof Error && "code" in cause && typeof cause.code === "string"
? cause.code
: undefined;
}
async function openLinuxPath(
absolutePath: string,
flags: number,
mode?: number,
): Promise<NodeFSP.FileHandle> {
const segments = absolutePath.split(NodePath.sep).filter(Boolean);
const fileName = segments.pop();
if (!fileName || segments.some((segment) => segment === "." || segment === "..")) {
throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`);
}
let directory = await NodeFS.promises.open(
NodePath.sep,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY,
);
try {
for (const segment of segments) {
// Each lookup is anchored to an already-open directory, so replacing its
// original pathname cannot redirect any later component.
const nextDirectory = await NodeFS.promises.open(
`/proc/self/fd/${directory.fd}/${segment}`,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY | NodeFS.constants.O_NOFOLLOW,
);
await directory.close();
directory = nextDirectory;
}
return await NodeFS.promises.open(
`/proc/self/fd/${directory.fd}/${fileName}`,
flags | NodeFS.constants.O_NOFOLLOW,
mode,
);
} finally {
await directory.close();
}
}
async function verifyFallbackHandle(
absolutePath: string,
handle: NodeFSP.FileHandle,
): Promise<NodeFSP.FileHandle> {
try {
const [canonicalPath, pathInfo, handleInfo] = await Promise.all([
NodeFS.promises.realpath(absolutePath),
NodeFS.promises.stat(absolutePath),
handle.stat(),
]);
if (
canonicalPath !== absolutePath ||
pathInfo.dev !== handleInfo.dev ||
pathInfo.ino !== handleInfo.ino
) {
throw new Error(`Path changed while it was being opened: ${absolutePath}`);
}
return handle;
} catch (cause) {
await handle.close();
throw cause;
}
}
async function openPathNoFollow(
absolutePath: string,
flags: number,
platform: NodeJS.Platform,
mode?: number,
): Promise<NodeFSP.FileHandle> {
if (!NodePath.isAbsolute(absolutePath) || NodePath.resolve(absolutePath) !== absolutePath) {
throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`);
}
if (platform === "darwin") {
return NodeFS.promises.open(absolutePath, flags | DARWIN_O_NOFOLLOW_ANY, mode);
}
if (platform === "linux") {
return openLinuxPath(absolutePath, flags, mode);
}
// Other platforms lack an openat-style primitive in Node. Keep the handle
// only when its identity still matches the canonical pathname.
const noFollow = NodeFS.constants.O_NOFOLLOW ?? 0;
const handle = await NodeFS.promises.open(absolutePath, flags | noFollow, mode);
return verifyFallbackHandle(absolutePath, handle);
}
export async function openReadableFileNoFollow(
absolutePath: string,
platform: NodeJS.Platform,
): Promise<{
readonly stream: NodeFS.ReadStream;
readonly size: number;
}> {
const handle = await openPathNoFollow(absolutePath, NodeFS.constants.O_RDONLY, platform);
try {
const info = await handle.stat();
if (!info.isFile()) {
throw new Error(`Expected a regular file: ${absolutePath}`);
}
return {
stream: handle.createReadStream({ autoClose: true }),
size: info.size,
};
} catch (cause) {
await handle.close();
throw cause;
}
}
export async function openWritableFileNoFollow(
absolutePath: string,
platform: NodeJS.Platform,
): Promise<NodeFSP.FileHandle> {
try {
return await openPathNoFollow(absolutePath, NodeFS.constants.O_WRONLY, platform);
} catch (cause) {
if (errnoCode(cause) !== "ENOENT") {
throw cause;
}
return openPathNoFollow(
absolutePath,
NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
platform,
0o666,
);
}
}
+21 -7
View File
@@ -47,6 +47,17 @@ export function useAssetUrls(
environmentId: EnvironmentId,
resources: ReadonlyArray<AssetResource>,
): ReadonlyArray<string | null> {
const states = useAssetUrlStates(environmentId, resources);
return useMemo(
() => states.map((state) => (state._tag === "Success" ? state.url : null)),
[states],
);
}
export function useAssetUrlStates(
environmentId: EnvironmentId,
resources: ReadonlyArray<AssetResource>,
): ReadonlyArray<AssetUrlState> {
const preparedConnection = usePreparedConnection(environmentId);
const results = useAtomValue(
assetEnvironment.createUrls({
@@ -56,13 +67,16 @@ export function useAssetUrls(
);
return useMemo(
() =>
preparedConnection._tag === "None"
? resources.map(() => null)
: results.map((result) =>
AsyncResult.isSuccess(result)
? resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl)
: null,
),
results.map((result): AssetUrlState => {
if (AsyncResult.isFailure(result)) {
return { _tag: "Failure" };
}
if (preparedConnection._tag === "None" || !AsyncResult.isSuccess(result)) {
return { _tag: "Loading" };
}
const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl);
return url === null ? { _tag: "Failure" } : { _tag: "Success", url };
}),
[preparedConnection, resources, results],
);
}
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vite-plus/test";
import { buildExpandedImagePreview } from "./ExpandedImagePreview";
describe("buildExpandedImagePreview", () => {
it("opens the selected image at its index in the available gallery", () => {
expect(
buildExpandedImagePreview(
[
{ id: "first", name: "first.png", previewUrl: "https://example.test/first.png" },
{ id: "missing", name: "missing.png" },
{ id: "second", name: "second.png", previewUrl: "https://example.test/second.png" },
],
"second",
),
).toEqual({
images: [
{ src: "https://example.test/first.png", name: "first.png" },
{ src: "https://example.test/second.png", name: "second.png" },
],
index: 1,
});
});
});
@@ -123,10 +123,11 @@ vi.mock("@pierre/diffs/react", () => {
});
vi.mock("~/assets/assetUrls", () => ({
useAssetUrlState: () => ({
_tag: "Success",
url: "https://environment.example/api/assets/image-token/tool-output.png",
}),
useAssetUrlStates: (_environmentId: unknown, resources: ReadonlyArray<unknown>) =>
resources.map(() => ({
_tag: "Success",
url: "https://environment.example/api/assets/image-token/tool-output.png",
})),
}));
function matchMedia() {
@@ -98,7 +98,7 @@ import {
type ParsedPreviewAnnotation,
} from "~/lib/previewAnnotation";
import { cn } from "~/lib/utils";
import { useAssetUrlState } from "~/assets/assetUrls";
import { useAssetUrlStates, type AssetUrlState } from "~/assets/assetUrls";
import { useUiStateStore } from "~/uiStateStore";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
@@ -1951,13 +1951,62 @@ function ImageOutputGallery({
threadRef: ScopedThreadRef;
className?: string;
}) {
const { activeThreadEnvironmentId, onImageExpand } = use(TimelineRowCtx);
const resources = useMemo(
() =>
images.map((image) => ({
_tag: "thread-image" as const,
threadId: threadRef.threadId,
activityId: EventId.make(image.entry.imageActivityId ?? image.entry.id),
})),
[images, threadRef.threadId],
);
const assetUrls = useAssetUrlStates(activeThreadEnvironmentId, resources);
const [failedUrls, setFailedUrls] = useState<ReadonlySet<string>>(() => new Set());
const previewImages = useMemo(
() =>
images.map((image, index) => {
const assetUrl = assetUrls[index];
return {
id: image.entry.id,
name: imageFileName(image.imagePath),
...(assetUrl?._tag === "Success" && !failedUrls.has(assetUrl.url)
? { previewUrl: assetUrl.url }
: {}),
};
}),
[assetUrls, failedUrls, images],
);
const handleImageFailure = useCallback((url: string) => {
setFailedUrls((current) => {
if (current.has(url)) return current;
const next = new Set(current);
next.add(url);
return next;
});
}, []);
const handleImageExpand = useCallback(
(imageId: string) => {
const preview = buildExpandedImagePreview(previewImages, imageId);
if (preview) onImageExpand(preview);
},
[onImageExpand, previewImages],
);
return (
<article
className={cn("flex max-w-full items-start gap-2 overflow-x-auto px-1 pb-1", className)}
aria-label={images.length === 1 ? "Image output" : "Image outputs"}
>
{images.map((image) => (
<ImageOutputThumbnail key={image.imagePath} image={image} threadRef={threadRef} />
{images.map((image, index) => (
<ImageOutputThumbnail
key={image.imagePath}
image={image}
assetUrl={assetUrls[index] ?? { _tag: "Loading" }}
failedUrls={failedUrls}
onImageFailure={handleImageFailure}
onImageExpand={handleImageExpand}
/>
))}
</article>
);
@@ -1965,21 +2014,22 @@ function ImageOutputGallery({
function ImageOutputThumbnail({
image,
threadRef,
assetUrl,
failedUrls,
onImageFailure,
onImageExpand,
}: {
image: TimelineImageOutput;
threadRef: ScopedThreadRef;
assetUrl: AssetUrlState;
failedUrls: ReadonlySet<string>;
onImageFailure: (url: string) => void;
onImageExpand: (imageId: string) => void;
}) {
const { activeThreadEnvironmentId, onImageExpand } = use(TimelineRowCtx);
const imageName = imageFileName(image.imagePath);
const assetUrl = useAssetUrlState(activeThreadEnvironmentId, {
_tag: "thread-image",
threadId: threadRef.threadId,
activityId: EventId.make(image.entry.imageActivityId ?? image.entry.id),
});
const [failedUrl, setFailedUrl] = useState<string | null>(null);
const loadedUrl = assetUrl._tag === "Success" && assetUrl.url !== failedUrl ? assetUrl.url : null;
const failed = assetUrl._tag === "Failure" || failedUrl !== null;
const loadedUrl =
assetUrl._tag === "Success" && !failedUrls.has(assetUrl.url) ? assetUrl.url : null;
const failed =
assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrls.has(assetUrl.url));
return (
<div className="shrink-0" data-image-view-activity-id={image.entry.id}>
@@ -1988,18 +2038,13 @@ function ImageOutputThumbnail({
type="button"
className="block size-32 cursor-zoom-in overflow-hidden rounded-xl border border-border/70 bg-muted/20 p-1 transition-colors hover:border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
aria-label={`Preview ${imageName}`}
onClick={() =>
onImageExpand({
images: [{ src: loadedUrl, name: imageName }],
index: 0,
})
}
onClick={() => onImageExpand(image.entry.id)}
>
<img
src={loadedUrl}
alt={imageName}
className="block size-full rounded-md object-contain"
onError={() => setFailedUrl(loadedUrl)}
onError={() => onImageFailure(loadedUrl)}
/>
</button>
) : failed ? (