diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts
index e1ba0742f3c90..b3737bec488dd 100644
--- a/apps/server/src/htmlRender/HtmlRender.test.ts
+++ b/apps/server/src/htmlRender/HtmlRender.test.ts
@@ -186,6 +186,34 @@ describe("HtmlRender", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect(
+ "refuses internal server paths and non-image size probes when inlining local images",
+ () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const config = yield* ServerConfig.ServerConfig;
+ const htmlRender = yield* HtmlRender.HtmlRender;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-guard-" });
+ const internalSvg = path.join(config.secretsDir, "secret.svg");
+ yield* fileSystem.makeDirectory(config.secretsDir, { recursive: true });
+ yield* fileSystem.writeFileString(internalSvg, "");
+ const hugeNonImage = path.join(directory, "not-an-image.png");
+ yield* fileSystem.writeFileString(hugeNonImage, "NOT_A_PNG");
+ yield* fileSystem.truncate(hugeNonImage, 11 * 1024 * 1024);
+
+ const error = yield* htmlRender
+ .prepare(`
`)
+ .pipe(Effect.flip);
+
+ expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
+ expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
+ internalSvg,
+ hugeNonImage,
+ ]);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("publishes the prepared page as an html thread attachment", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.ts
index 39cb7a463dbd4..f2d1c750eac1f 100644
--- a/apps/server/src/htmlRender/HtmlRender.ts
+++ b/apps/server/src/htmlRender/HtmlRender.ts
@@ -26,7 +26,6 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
-import * as Stream from "effect/Stream";
import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { openMediaFile } from "../assets/MediaFile.ts";
@@ -146,12 +145,16 @@ export interface HtmlPreview {
export class HtmlRender extends Context.Service<
HtmlRender,
{
- readonly prepare: (html: string) => Effect.Effect;
+ readonly prepare: (
+ html: string,
+ options?: { readonly allowLocalImages?: boolean | undefined },
+ ) => Effect.Effect;
readonly publish: (
input: HtmlRenderSource & {
readonly threadId: ThreadId;
readonly title: string;
readonly height: number;
+ readonly allowLocalImages?: boolean | undefined;
},
) => Effect.Effect<
HtmlRenderReference,
@@ -164,6 +167,7 @@ export class HtmlRender extends Context.Service<
input: HtmlRenderSource & {
readonly width?: number | undefined;
readonly appearance?: ThemeAppearance | undefined;
+ readonly allowLocalImages?: boolean | undefined;
},
) => Effect.Effect<
HtmlPreview,
@@ -267,63 +271,80 @@ const afterDoctype = (text: string, from: number) => {
return -1;
};
-const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
+const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (
+ html: string,
+ isServerInternalPath: (filePath: string) => Effect.Effect,
+) {
const fileSystem = yield* FileSystem.FileSystem;
const references = findLocalImages(html);
- const files = yield* Effect.forEach(
- [...new Set(references.map((reference) => reference.path))],
- (path) =>
- fileSystem.stat(filePathFor(path)).pipe(
- Effect.map((info) => ({
- path,
- size: info.type === "File" ? Number(info.size) : undefined,
- })),
- Effect.orElseSucceed(() => ({ path, size: undefined })),
- ),
- { concurrency: 8 },
- );
- const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
- if (oversized?.size !== undefined) {
- return yield* new HtmlRenderImageTooLargeError({
- path: oversized.path,
- sizeBytes: oversized.size,
- });
- }
- const sizes = new Map(files.map((file) => [file.path, file.size]));
- const pageBytes = references.reduce((total, reference) => {
- const size = sizes.get(reference.path);
- return size === undefined
- ? total
- : total +
- dataUriPrefix(reference.path).length +
- Math.ceil(size / 3) * 4 -
- Buffer.byteLength(reference.path);
- }, Buffer.byteLength(html));
- if (pageBytes > MAX_PAGE_BYTES) {
- return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
- }
- // Files can grow after stat; bound each read and stop when accumulated images cannot fit.
+ const uniquePaths = [...new Set(references.map((reference) => reference.path))];
let readBytes = 0;
const images = yield* Effect.forEach(
- files.filter((file) => file.size !== undefined),
- (file) =>
+ uniquePaths,
+ (referencePath) =>
Effect.gen(function* () {
- const read = yield* fileSystem
- .stream(filePathFor(file.path), { bytesToRead: MAX_IMAGE_BYTES + 1 })
- .pipe(Stream.mkUint8Array, Effect.option);
- if (Option.isNone(read) || !isImageBytes(read.value)) return [];
- const bytes = read.value;
- if (bytes.byteLength > MAX_IMAGE_BYTES) {
- return yield* new HtmlRenderImageTooLargeError({
- path: file.path,
- sizeBytes: bytes.byteLength,
- });
+ const filePath = filePathFor(referencePath);
+ if (isNetworkPath(filePath)) return [];
+ const realPath = yield* fileSystem.realPath(filePath).pipe(Effect.option);
+ if (Option.isNone(realPath) || (yield* isServerInternalPath(realPath.value))) {
+ return [];
}
- readBytes += Math.ceil(bytes.byteLength / 3) * 4;
+ const read = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const file = yield* openMediaFile(realPath.value).pipe(Effect.option);
+ if (Option.isNone(file) || file.value === null) return null;
+ const opened = file.value;
+ const head = yield* Effect.tryPromise({
+ try: () => {
+ const buffer = Buffer.alloc(Math.min(Number(opened.info.size), 4096));
+ return opened.handle
+ .read(buffer, 0, buffer.length, 0)
+ .then(({ bytesRead }) => buffer.subarray(0, bytesRead));
+ },
+ catch: (cause) => new HtmlRenderFileError({ path: referencePath, cause }),
+ }).pipe(Effect.option);
+ if (Option.isNone(head) || !isImageBytes(head.value)) return null;
+ if (opened.info.size > BigInt(MAX_IMAGE_BYTES)) {
+ return yield* new HtmlRenderImageTooLargeError({
+ path: referencePath,
+ sizeBytes: Number(opened.info.size),
+ });
+ }
+ const bytes = yield* Effect.tryPromise({
+ try: async () => {
+ const limit = Math.min(Number(opened.info.size), MAX_IMAGE_BYTES + 1);
+ const buffer = Buffer.alloc(limit);
+ let filled = 0;
+ while (filled < buffer.length) {
+ const { bytesRead } = await opened.handle.read(
+ buffer,
+ filled,
+ buffer.length - filled,
+ filled,
+ );
+ if (bytesRead === 0) break;
+ filled += bytesRead;
+ }
+ return buffer.subarray(0, filled);
+ },
+ catch: (cause) => new HtmlRenderFileError({ path: referencePath, cause }),
+ }).pipe(Effect.option);
+ if (Option.isNone(bytes) || !isImageBytes(bytes.value)) return null;
+ if (bytes.value.byteLength > MAX_IMAGE_BYTES) {
+ return yield* new HtmlRenderImageTooLargeError({
+ path: referencePath,
+ sizeBytes: bytes.value.byteLength,
+ });
+ }
+ return bytes.value;
+ }),
+ );
+ if (read === null) return [];
+ readBytes += Math.ceil(read.byteLength / 3) * 4;
if (readBytes > MAX_PAGE_BYTES) {
return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
}
- return [{ path: file.path, bytes }];
+ return [{ path: referencePath, bytes: read }];
}),
{ concurrency: 4 },
).pipe(Effect.map((entries) => entries.flat()));
@@ -352,7 +373,7 @@ const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (h
}
return {
html: inlined,
- missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
+ missing: uniquePaths.filter((referencePath) => !dataUris.has(referencePath)),
};
});
@@ -486,12 +507,22 @@ const make = Effect.gen(function* () {
"path" in input ? readPageFile(input.path) : Effect.succeed(input.html);
// The bootstrap goes in first so its head scan never runs over inlined image data.
- const inline = (html: string) =>
- inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
+ const inline = (html: string, allowLocalImages = true) => {
+ const bootstrapped = injectHtmlRenderBootstrap(html);
+ if (!allowLocalImages) {
+ return Effect.succeed({ html: bootstrapped, missing: [] as Array });
+ }
+ return inlineLocalImages(bootstrapped, isServerInternalPath).pipe(
+ Effect.provideContext(services),
+ );
+ };
- const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
+ const prepare = Effect.fn("HtmlRender.prepare")(function* (
+ html: string,
+ options?: { readonly allowLocalImages?: boolean | undefined },
+ ) {
yield* rejectViewportHeight(html);
- const inlined = yield* inline(html);
+ const inlined = yield* inline(html, options?.allowLocalImages);
if (inlined.missing.length > 0) {
return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
}
@@ -503,10 +534,11 @@ const make = Effect.gen(function* () {
readonly threadId: ThreadId;
readonly title: string;
readonly height: number;
+ readonly allowLocalImages?: boolean | undefined;
},
) {
const source = yield* readSource(input);
- const html = yield* prepare(source);
+ const html = yield* prepare(source, { allowLocalImages: input.allowLocalImages });
// The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
const attachmentId = createAttachmentId(input.threadId, "html");
const filePath =
@@ -563,6 +595,7 @@ const make = Effect.gen(function* () {
input: HtmlRenderSource & {
readonly width?: number | undefined;
readonly appearance?: ThemeAppearance | undefined;
+ readonly allowLocalImages?: boolean | undefined;
},
) {
const width = Math.min(
@@ -572,7 +605,7 @@ const make = Effect.gen(function* () {
const appearance = input.appearance ?? "dark";
const source = yield* readSource(input);
yield* rejectViewportHeight(source);
- const inlined = yield* inline(source);
+ const inlined = yield* inline(source, input.allowLocalImages);
const executable = yield* previewBrowser.executable;
const theme = htmlRenderTheme(
appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index c1d35ace86940..4d4fd080dde83 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -1,4 +1,5 @@
import * as AssetSigner from "../../assets/AssetSigner.ts";
+import { resolveAttachmentPathById } from "../../attachmentStore.ts";
import * as DocumentText from "../../provider/DocumentText.ts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -28,6 +29,8 @@ import * as DateTime from "effect/DateTime";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -384,14 +387,49 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both
expect(yield* byPath(name, scope), name).toContain("only full-access threads");
expect(yield* byPath(name, fullAccess), name).toContain("not a readable HTML document");
}
+ // Inlining a local image is a file read too, so it follows the same rule.
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const config = yield* ServerConfig.ServerConfig;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-img-" });
+ const image = path.join(directory, "secret.svg");
+ const svg = '';
+ yield* fileSystem.writeFileString(image, svg);
+ const renderedImage = (caller: McpInvocationContext.McpInvocationScope) =>
+ server
+ .callTool({
+ name: "html_render",
+ arguments: { html: `
`, title: "Image", height: 240 },
+ })
+ .pipe(
+ Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
+ Effect.provideService(McpSchema.McpServerClient, client),
+ Effect.flatMap((result) => {
+ const attachmentId = htmlRenderFromToolItem({
+ toolName: "t3-code.html_render",
+ output: result.structuredContent,
+ })?.attachmentId;
+ const stored =
+ attachmentId &&
+ resolveAttachmentPathById({ attachmentsDir: config.attachmentsDir, attachmentId });
+ return fileSystem.readFileString(stored || "/t3-missing-attachment");
+ }),
+ );
+ const dataUri = `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
+ const cappedFullAccess = { ...fullAccess, runtimeModeCeiling: "approval-required" as const };
+ expect(yield* renderedImage(scope)).not.toContain(dataUri);
+ expect(yield* renderedImage(cappedFullAccess)).not.toContain(dataUri);
+ expect(yield* renderedImage(fullAccess)).toContain(dataUri);
}).pipe(
Effect.provide(
McpHttpServer.layerHtmlToolkit.pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(McpProviderSessions.layer),
Layer.provide(PreviewBrowser.layer),
- Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" })),
- Layer.provide(
+ Layer.provideMerge(
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" }),
+ ),
+ Layer.provideMerge(
DocumentText.layer.pipe(
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
),
diff --git a/apps/server/src/mcp/toolkits/html/handlers.ts b/apps/server/src/mcp/toolkits/html/handlers.ts
index 3cba937186b89..68651b0e3e4d4 100644
--- a/apps/server/src/mcp/toolkits/html/handlers.ts
+++ b/apps/server/src/mcp/toolkits/html/handlers.ts
@@ -1,4 +1,4 @@
-import { OrchestratorMcpFailure } from "@t3tools/contracts";
+import { isRuntimeModeAbove, OrchestratorMcpFailure } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as HtmlRender from "../../../htmlRender/HtmlRender.ts";
@@ -22,14 +22,21 @@ const toFailure = (error: { readonly _tag: string; readonly message: string }) =
message: error.message,
});
-// The server reads the file for the caller, so only a thread that reads files without asking may
-// pass a path; a supervised thread passes the HTML its provider already let it read.
+// The server reads local files for the caller, so only a thread that reads files without asking
+// may pass a path or have local image paths inlined; supervised threads pass inline HTML only.
const pageSource = Effect.fn("HtmlToolkit.pageSource")(function* (input: {
readonly html?: string | undefined;
readonly path?: string | undefined;
}) {
+ const { limits, scope } = yield* loadCaller();
+ const ceiling = scope.runtimeModeCeiling ?? "full-access";
+ const allowLocalImages =
+ limits.runtimeMode === "full-access" && !isRuntimeModeAbove("full-access", ceiling);
if (input.html !== undefined && input.path === undefined) {
- return { html: input.html } satisfies HtmlRender.HtmlRenderSource;
+ return {
+ source: { html: input.html } satisfies HtmlRender.HtmlRenderSource,
+ allowLocalImages,
+ };
}
if (input.path === undefined || input.html !== undefined) {
return yield* new OrchestratorMcpFailure({
@@ -37,14 +44,16 @@ const pageSource = Effect.fn("HtmlToolkit.pageSource")(function* (input: {
message: "Pass exactly one of html or path.",
});
}
- const { limits } = yield* loadCaller();
- if (limits.runtimeMode !== "full-access") {
+ if (!allowLocalImages) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Pass html instead of path: only full-access threads may pass a path.",
});
}
- return { path: input.path } satisfies HtmlRender.HtmlRenderSource;
+ return {
+ source: { path: input.path } satisfies HtmlRender.HtmlRenderSource,
+ allowLocalImages,
+ };
});
const handlers = {
@@ -52,9 +61,9 @@ const handlers = {
html_preview: McpToolAccess.readsAsCaller((input) =>
Effect.gen(function* () {
const htmlRender = yield* HtmlRender.HtmlRender;
- const source = yield* pageSource(input);
+ const { source, allowLocalImages } = yield* pageSource(input);
const { png, ...preview } = yield* htmlRender
- .preview({ ...source, width: input.width, appearance: input.appearance })
+ .preview({ ...source, allowLocalImages, width: input.width, appearance: input.appearance })
.pipe(Effect.mapError(toFailure));
return {
...preview,
@@ -72,9 +81,15 @@ const handlers = {
const scope = yield* McpInvocationContext.McpInvocationContext;
const { thread } = yield* McpInvocationContext.requireThreadScope(scope, "html_render");
const htmlRender = yield* HtmlRender.HtmlRender;
- const source = yield* pageSource(input);
+ const { source, allowLocalImages } = yield* pageSource(input);
const reference = yield* htmlRender
- .publish({ ...source, threadId: thread.threadId, title: input.title, height: input.height })
+ .publish({
+ ...source,
+ allowLocalImages,
+ threadId: thread.threadId,
+ title: input.title,
+ height: input.height,
+ })
.pipe(Effect.mapError(toFailure));
return {
htmlRender: reference,