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
28 changes: 28 additions & 0 deletions apps/server/src/htmlRender/HtmlRender.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<svg><text>INTERNAL</text></svg>");
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(`<img src="${internalSvg}"><img src="${hugeNonImage}">`)
.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;
Expand Down
147 changes: 90 additions & 57 deletions apps/server/src/htmlRender/HtmlRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -146,12 +145,16 @@ export interface HtmlPreview {
export class HtmlRender extends Context.Service<
HtmlRender,
{
readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
readonly prepare: (
html: string,
options?: { readonly allowLocalImages?: boolean | undefined },
) => Effect.Effect<string, HtmlRenderPrepareError>;
readonly publish: (
input: HtmlRenderSource & {
readonly threadId: ThreadId;
readonly title: string;
readonly height: number;
readonly allowLocalImages?: boolean | undefined;
},
) => Effect.Effect<
HtmlRenderReference,
Expand All @@ -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,
Expand Down Expand Up @@ -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<boolean>,
) {
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()));
Expand Down Expand Up @@ -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)),
};
});

Expand Down Expand Up @@ -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<string> });
}
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 });
}
Expand All @@ -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 =
Expand Down Expand Up @@ -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(
Expand All @@ -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,
Expand Down
42 changes: 40 additions & 2 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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 = '<svg xmlns="http://www.w3.org/2000/svg"><text>SECRET</text></svg>';
yield* fileSystem.writeFileString(image, svg);
const renderedImage = (caller: McpInvocationContext.McpInvocationScope) =>
server
.callTool({
name: "html_render",
arguments: { html: `<img src="${image}">`, 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)),
),
Expand Down
Loading
Loading