Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - tests inject swaps at the native open boundary.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
4import * as NodeFSP from "node:fs/promises";
5import {
6 AssetAccessError,
7 AssetPreviewTypeValidationError,
8 ThreadId,
9 TurnItemId,
10} from "@t3tools/contracts";
11import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
12import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
13import { describe, expect, it } from "@effect/vitest";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Redacted from "effect/Redacted";
19import * as Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Schema from "effect/Schema";
22import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
23import { vi } from "vite-plus/test";
24
25import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26import * as ServerConfig from "../config.ts";
27import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
28import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
29import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
30import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
31import { assetFileResponse } from "../http.ts";
32import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
33import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
34import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
35import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
36import { githubMediaResponse } from "./GitHubMediaFetch.ts";
37import * as HostProcess from "@t3tools/shared/HostProcess";
38
39vi.mock("node:fs/promises", async (importOriginal) => {
40 const actual = await importOriginal<typeof NodeFSP>();
41 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
42});
43
44const layerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
45 prefix: "t3-asset-access-test-",
46});
47const screenshotPng = new Uint8Array(24);
48screenshotPng.set([
49 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52,
50]);
51new DataView(screenshotPng.buffer).setUint32(16, 390);
52new DataView(screenshotPng.buffer).setUint32(20, 844);
53const screenshotItem = {
54 id: TurnItemId.make("tool-screenshot"),
55 type: "dynamic_tool" as const,
56 threadId: ThreadId.make("thread-1"),
57 runId: null,
58 nodeId: null,
59 providerThreadId: null,
60 providerTurnId: null,
61 nativeItemRef: null,
62 parentItemId: null,
63 ordinal: 1,
64 status: "completed" as const,
65 title: null,
66 toolName: "mcp__t3-code__device_screenshot",
67 input: { deviceId: "phone" },
68 output: {
69 content: [
70 {
71 type: "image",
72 source: {
73 type: "base64",
74 media_type: "image/png",
75 data: Buffer.from(screenshotPng).toString("base64"),
76 },
77 },
78 ],
79 },
80 startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),
81 completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
82 updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
83};
84
85const oversizedScreenshotItem = {
86 ...screenshotItem,
87 id: TurnItemId.make("tool-screenshot-oversized"),
88 output: {
89 content: [
90 {
91 type: "image",
92 source: { type: "base64", media_type: "image/png", data: "A".repeat(14 * 1024 * 1024) },
93 },
94 ],
95 },
96};
97
98const layerTest = Layer.mergeAll(
99 NodeHttpPlatform.layer,
100 Layer.mock(Orchestrator.OrchestratorV2)({
101 getTurnItem: ({ itemId }) =>
102 Effect.succeed(
103 itemId === screenshotItem.id
104 ? screenshotItem
105 : itemId === oversizedScreenshotItem.id
106 ? oversizedScreenshotItem
107 : null,
108 ),
109 }),
110 layerConfig,
111 WorkspacePaths.layer,
112 ProjectFaviconResolver.layer.pipe(
113 Layer.provide(WorkspacePaths.layer),
114 Layer.provide(T3ProjectFileLoader.layer),
115 ),
116 NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
117 ServerSecretStore.layer.pipe(Layer.provide(layerConfig)),
118).pipe(Layer.provideMerge(NodeServices.layer));
119
120describe("AssetAccess", () => {
121 describe("readMcpAppHtml", () => {
122 it.effect("accepts snapshots at the stored HTML byte limit", () =>
123 Effect.gen(function* () {
124 const fileSystem = yield* FileSystem.FileSystem;
125 const path = yield* Path.Path;
126 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
127 const file = path.join(directory, "app.html");
128 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
129 yield* fileSystem.writeFile(file, new Uint8Array(limit).fill(120));
130
131 const bytes = yield* readMcpAppHtml(file);
132 expect(bytes?.byteLength).toBe(limit);
133 expect(bytes?.every((byte) => byte === 120)).toBe(true);
134 }).pipe(Effect.provide(NodeServices.layer)),
135 );
136
137 it.effect("rejects snapshots one byte past the limit and much larger files", () =>
138 Effect.gen(function* () {
139 const fileSystem = yield* FileSystem.FileSystem;
140 const path = yield* Path.Path;
141 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
142 const file = path.join(directory, "app.html");
143 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
144 for (const size of [limit + 1, limit * 2]) {
145 yield* fileSystem.writeFile(file, new Uint8Array(size).fill(120));
146 expect(yield* readMcpAppHtml(file)).toBeNull();
147 }
148 }).pipe(Effect.provide(NodeServices.layer)),
149 );
150
151 it.effect("preserves UTF-8 bytes across stream chunks and accepts empty snapshots", () =>
152 Effect.gen(function* () {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
156 const file = path.join(directory, "app.html");
157 for (const html of ["", "<body>" + "☃".repeat(100_000) + "</body>"]) {
158 const expected = new TextEncoder().encode(html);
159 yield* fileSystem.writeFile(file, expected);
160 const bytes = yield* readMcpAppHtml(file);
161 expect(bytes?.byteLength).toBe(expected.byteLength);
162 expect(bytes && new TextDecoder().decode(bytes)).toBe(html);
163 }
164 }).pipe(Effect.provide(NodeServices.layer)),
165 );
166
167 // regression: #17026 apply host color scheme to saved MCP apps
168 it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
169 Effect.gen(function* () {
170 const fileSystem = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
173 const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
174 expect(error._tag).toBe("PlatformError");
175 expect(error.reason._tag).toBe("NotFound");
176 }).pipe(Effect.provide(NodeServices.layer)),
177 );
178 });
179
180 it.effect("loads private media immediately after login with the GitHub credential", () => {
181 let lookups = 0;
182 const authorizations: Array<string | undefined> = [];
183 return Effect.gen(function* () {
184 const asset = {
185 url: "https://raw.githubusercontent.com/owner/repo/main/shot.png",
186 cwd: "/repo",
187 expiresAt: Number.MAX_SAFE_INTEGER,
188 };
189 expect((yield* githubMediaResponse(asset, {})).status).toBe(404);
190 expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
191 expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
192 expect(lookups).toBe(3);
193 expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
194 }).pipe(
195 Effect.provide(
196 Layer.mock(GitHubCredentials.GitHubCredentials)({
197 get: (host) =>
198 ++lookups === 1
199 ? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }))
200 : Effect.succeed({
201 host,
202 token: Redacted.make("signed-in"),
203 source: "gh" as const,
204 fingerprint: "fingerprint",
205 }),
206 }),
207 ),
208 Effect.provideService(
209 HttpClient.HttpClient,
210 HttpClient.make((request) => {
211 authorizations.push(request.headers.authorization);
212 return Effect.succeed(
213 HttpClientResponse.fromWeb(
214 request,
215 new Response(null, {
216 status: request.headers.authorization ? 200 : 404,
217 headers: { "content-type": "image/png" },
218 }),
219 ),
220 );
221 }),
222 ),
223 Effect.scoped,
224 );
225 });
226
227 it.effect("serves an image a tool returned inline from the stored item", () =>
228 Effect.gen(function* () {
229 const resource = {
230 _tag: "tool-output-image" as const,
231 threadId: screenshotItem.threadId,
232 itemId: screenshotItem.id,
233 index: 0,
234 };
235 const result = yield* issueAssetUrl({ resource });
236 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
237 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
238 const separator = suffix.indexOf("/");
239 expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({
240 kind: "bytes",
241 mimeType: "image/png",
242 bytes: Buffer.from(screenshotPng),
243 });
244 const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(
245 Effect.flip,
246 );
247 expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");
248 const oversized = yield* issueAssetUrl({
249 resource: { ...resource, itemId: oversizedScreenshotItem.id },
250 }).pipe(Effect.flip);
251 expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");
252 }).pipe(Effect.provide(layerTest)),
253 );
254
255 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
256 Effect.gen(function* () {
257 const fs = yield* FileSystem.FileSystem;
258 const path = yield* Path.Path;
259 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
260 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
261 for (const [name, mimeType] of [
262 ["screenshot.png", "image/png"],
263 ["recording.mp4", "video/mp4"],
264 ["recording.webm", "video/webm"],
265 ["report.html", "text/html"],
266 ["report.pdf", "application/pdf"],
267 ] as const) {
268 const filePath = path.join(outside, name);
269 yield* fs.writeFileString(filePath, "media");
270 const canonicalFile = yield* fs.realPath(filePath);
271 const result = yield* issueAssetUrl({
272 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
273 workspaceRoot: root,
274 });
275 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
276 const separator = suffix.indexOf("/");
277 const token = suffix.slice(0, separator);
278 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
279 kind: "file",
280 path: canonicalFile,
281 mimeType,
282 });
283 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
284 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
285 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
286 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
287 }
288 }).pipe(Effect.provide(layerTest)),
289 );
290
291 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
292 Effect.gen(function* () {
293 const fs = yield* FileSystem.FileSystem;
294 const path = yield* Path.Path;
295 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
296 const root = path.join(directory, "workspace");
297 yield* fs.makeDirectory(root);
298 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
299 const filePath = path.resolve(root, relativePath);
300 yield* fs.writeFileString(filePath, "media");
301 const result = yield* issueAssetUrl({
302 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
303 workspaceRoot: root,
304 });
305 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
306 const separator = suffix.indexOf("/");
307 expect(
308 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
309 ).toMatchObject({
310 kind: "file",
311 path: yield* fs.realPath(filePath),
312 });
313 }
314 }).pipe(Effect.provide(layerTest)),
315 );
316
317 it.effect("resolves home-relative media paths independently of the workspace", () =>
318 Effect.gen(function* () {
319 const fs = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
322 const home = path.join(directory, "var", "home", "alice");
323 const filePath = path.join(home, "Downloads", "repro.mp4");
324 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
325 yield* fs.writeFileString(filePath, "recording bytes");
326 const canonicalFile = yield* fs.realPath(filePath);
327 yield* Effect.gen(function* () {
328 for (const workspaceRoot of [
329 path.join(home, "project"),
330 path.join(directory, "srv", "project"),
331 undefined,
332 ]) {
333 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
334 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
335 const result = yield* issueAssetUrl({
336 resource: {
337 _tag: "media-file",
338 threadId: ThreadId.make("thread-1"),
339 path: requestedPath,
340 },
341 ...(workspaceRoot ? { workspaceRoot } : {}),
342 });
343 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
344 const separator = suffix.indexOf("/");
345 const asset = yield* resolveAsset(
346 suffix.slice(0, separator),
347 suffix.slice(separator + 1),
348 );
349 expect(asset).toMatchObject({
350 kind: "file",
351 path: canonicalFile,
352 mimeType: "video/mp4",
353 });
354 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
355 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
356 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
357 }
358 }
359 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
360 }).pipe(Effect.provide(layerTest)),
361 );
362
363 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
364 // Windows user's NTLM credentials to attacker.test.
365 it.effect("never resolves a network media path outside the thread's project", () =>
366 Effect.gen(function* () {
367 const fs = yield* FileSystem.FileSystem;
368 const path = yield* Path.Path;
369 const resolved: Array<string> = [];
370 const recordingFileSystem = FileSystem.FileSystem.of({
371 ...fs,
372 realPath: (requestedPath) => {
373 resolved.push(requestedPath);
374 return Effect.fail(
375 PlatformError.systemError({
376 _tag: "NotFound",
377 module: "FileSystem",
378 method: "realPath",
379 pathOrDescriptor: requestedPath,
380 }),
381 );
382 },
383 });
384 const share = "//nas.test/share/project";
385 for (const resource of [
386 {
387 _tag: "media-file",
388 threadId: ThreadId.make("thread-1"),
389 path: "//attacker.test/s/a.png",
390 },
391 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
392 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
393 ] as const) {
394 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
395 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
396 Effect.flip,
397 );
398 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
399 }
400 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
401 }).pipe(Effect.provide(layerTest)),
402 );
403
404 it.effect.skipIf(!symlinksSupported)(
405 "rejects non-previewable files, disguised targets, and directories",
406 () =>
407 Effect.gen(function* () {
408 const fs = yield* FileSystem.FileSystem;
409 const path = yield* Path.Path;
410 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
411 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
412 const filePath = path.join(root, name);
413 yield* fs.writeFileString(filePath, "not media");
414 const error = yield* issueAssetUrl({
415 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
416 }).pipe(Effect.flip);
417 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
418 }
419 const disguisedPath = path.join(root, "disguised.png");
420 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
421 const disguisedError = yield* issueAssetUrl({
422 resource: {
423 _tag: "media-file",
424 threadId: ThreadId.make("thread-1"),
425 path: disguisedPath,
426 },
427 }).pipe(Effect.flip);
428 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
429 const directoryPath = path.join(root, "directory.png");
430 yield* fs.makeDirectory(directoryPath);
431 const directoryError = yield* issueAssetUrl({
432 resource: {
433 _tag: "media-file",
434 threadId: ThreadId.make("thread-1"),
435 path: directoryPath,
436 },
437 }).pipe(Effect.flip);
438 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
439 }).pipe(Effect.provide(layerTest)),
440 );
441
442 it.effect.skipIf(!symlinksSupported)(
443 "binds media URLs to the canonical target and rejects symlink substitution",
444 () =>
445 Effect.gen(function* () {
446 const fs = yield* FileSystem.FileSystem;
447 const path = yield* Path.Path;
448 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
449 const filePath = path.join(root, "actual.svg");
450 const aliasPath = path.join(root, "alias.png");
451 const replacementPath = path.join(root, "other.svg");
452 yield* fs.writeFileString(filePath, "<svg/>");
453 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
454 yield* fs.symlink(filePath, aliasPath);
455 const canonicalFile = yield* fs.realPath(filePath);
456 const result = yield* issueAssetUrl({
457 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
458 });
459 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
460 const separator = suffix.indexOf("/");
461 const token = suffix.slice(0, separator);
462 const name = suffix.slice(separator + 1);
463 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
464 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
465 yield* fs.remove(aliasPath);
466 yield* fs.symlink(replacementPath, aliasPath);
467 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
468 yield* fs.remove(filePath);
469 yield* fs.symlink(replacementPath, filePath);
470 expect(yield* resolveAsset(token, name)).toBeNull();
471 }).pipe(Effect.provide(layerTest)),
472 );
473
474 it.effect.skipIf(!symlinksSupported)(
475 "keeps full and partial responses bound to the file opened during resolution",
476 () =>
477 Effect.gen(function* () {
478 const fs = yield* FileSystem.FileSystem;
479 const path = yield* Path.Path;
480 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
481 const filePath = path.join(root, "recording.mp4");
482 const savedPath = path.join(root, "saved.mp4");
483 const secretPath = path.join(root, "secret.txt");
484 yield* fs.writeFileString(filePath, "0123456789");
485 yield* fs.writeFileString(secretPath, "private information");
486 const result = yield* issueAssetUrl({
487 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
488 });
489 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
490 const separator = suffix.indexOf("/");
491 for (const [range, expected, status] of [
492 [undefined, "0123456789", 200],
493 ["bytes=2-5", "2345", 206],
494 ] as const) {
495 const asset = yield* resolveAsset(
496 suffix.slice(0, separator),
497 suffix.slice(separator + 1),
498 );
499 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
500
501 yield* fs.rename(filePath, savedPath);
502 yield* fs.symlink(secretPath, filePath);
503 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
504 expect(response.status).toBe(status);
505 expect(response.headers.get("content-length")).toBe(String(expected.length));
506 expect(yield* Effect.promise(() => response.text())).toBe(expected);
507 yield* fs.remove(filePath);
508 yield* fs.rename(savedPath, filePath);
509 }
510 }).pipe(Effect.provide(layerTest)),
511 );
512
513 it.effect.skipIf(!symlinksSupported)(
514 "rejects a symlink swapped in after canonical validation but before open",
515 () =>
516 Effect.gen(function* () {
517 const fs = yield* FileSystem.FileSystem;
518 const path = yield* Path.Path;
519 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
520 const filePath = path.join(root, "recording.mp4");
521 const secretPath = path.join(root, "secret.txt");
522 yield* fs.writeFileString(filePath, "video");
523 yield* fs.writeFileString(secretPath, "secret");
524 const canonicalPath = yield* fs.realPath(filePath);
525 const result = yield* issueAssetUrl({
526 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
527 });
528 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
529 const separator = suffix.indexOf("/");
530 const swappingFileSystem = FileSystem.FileSystem.of({
531 ...fs,
532 stat: Effect.fn(function* (requestedPath) {
533 const info = yield* fs.stat(requestedPath);
534 if (requestedPath === canonicalPath) {
535 yield* fs.remove(filePath);
536 yield* fs.symlink(secretPath, filePath);
537 }
538 return info;
539 }),
540 });
541 expect(
542 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
543 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
544 ),
545 ).toBeNull();
546 }).pipe(Effect.provide(layerTest)),
547 );
548
549 it.effect.skipIf(!symlinksSupported)(
550 "rejects an ancestor symlink race even when canonical path rechecks would pass",
551 () =>
552 Effect.gen(function* () {
553 const fs = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
556 const publicDirectory = path.join(root, "public");
557 const privateDirectory = path.join(root, "private");
558 yield* fs.makeDirectory(publicDirectory);
559 yield* fs.makeDirectory(privateDirectory);
560 const filePath = path.join(publicDirectory, "recording.mp4");
561 yield* fs.writeFileString(filePath, "public video");
562 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
563 const canonicalPath = yield* fs.realPath(filePath);
564 const result = yield* issueAssetUrl({
565 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
566 });
567 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
568 const separator = suffix.indexOf("/");
569 const native = yield* Effect.promise(() =>
570 vi.importActual<typeof NodeFSP>("node:fs/promises"),
571 );
572 const savedDirectory = path.join(root, "saved");
573 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
574 await native.unlink(publicDirectory);
575 await native.rename(savedDirectory, publicDirectory);
576 const canonical = await native.realpath(canonicalPath);
577 await native.rename(publicDirectory, savedDirectory);
578 await native.symlink(privateDirectory, publicDirectory, "junction");
579 return canonical;
580 });
581 yield* Effect.addFinalizer(() =>
582 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
583 );
584 const swappingFileSystem = FileSystem.FileSystem.of({
585 ...fs,
586 realPath: Effect.fn(function* (requestedPath) {
587 const canonical = yield* fs.realPath(requestedPath);
588 if (requestedPath === canonicalPath) {
589 yield* fs.rename(publicDirectory, savedDirectory);
590 yield* Effect.promise(() =>
591 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
592 );
593 }
594 return canonical;
595 }),
596 });
597 expect(
598 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
599 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
600 ),
601 ).toBeNull();
602 }).pipe(Effect.provide(layerTest)),
603 );
604
605 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
606 Effect.gen(function* () {
607 const fs = yield* FileSystem.FileSystem;
608 const path = yield* Path.Path;
609 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
610 const filePath = path.join(root, "recording.mp4");
611 yield* fs.writeFileString(filePath, "original");
612 const input = {
613 resource: {
614 _tag: "media-file" as const,
615 threadId: ThreadId.make("thread-1"),
616 path: filePath,
617 },
618 };
619 const original = yield* issueAssetUrl(input);
620 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
621 const separator = suffix.indexOf("/");
622 const token = suffix.slice(0, separator);
623 const name = suffix.slice(separator + 1);
624 yield* fs.writeFileString(filePath, "in-place edit");
625 const edited = yield* resolveAsset(token, name);
626 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
627 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
628 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
629
630 const replacement = path.join(root, "replacement.mp4");
631 yield* fs.writeFileString(replacement, "replacement");
632 yield* fs.rename(replacement, filePath);
633 expect(yield* resolveAsset(token, name)).toBeNull();
634
635 const renewed = yield* issueAssetUrl(input);
636 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
637 const renewedSeparator = renewedSuffix.indexOf("/");
638 const renewedAsset = yield* resolveAsset(
639 renewedSuffix.slice(0, renewedSeparator),
640 renewedSuffix.slice(renewedSeparator + 1),
641 );
642 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
643 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
644 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
645 yield* fs.remove(filePath);
646 expect(
647 yield* resolveAsset(
648 renewedSuffix.slice(0, renewedSeparator),
649 renewedSuffix.slice(renewedSeparator + 1),
650 ),
651 ).toBeNull();
652 }).pipe(Effect.provide(layerTest)),
653 );
654
655 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
656 Effect.gen(function* () {
657 const fileSystem = yield* FileSystem.FileSystem;
658 const path = yield* Path.Path;
659 const root = yield* fileSystem.makeTempDirectoryScoped({
660 prefix: "t3-asset-workspace-",
661 });
662 const htmlPath = path.join(root, "report.html");
663 const cssPath = path.join(root, "report.css");
664 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
665 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
666 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
667 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
668 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
669
670 const result = yield* issueAssetUrl({
671 resource: {
672 _tag: "workspace-file",
673 threadId: ThreadId.make("thread-1"),
674 path: htmlPath,
675 },
676 workspaceRoot: root,
677 });
678 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
679 const separatorIndex = suffix.indexOf("/");
680 const token = suffix.slice(0, separatorIndex);
681
682 expect(yield* resolveAsset(token, "report.html")).toEqual({
683 kind: "file",
684 path: canonicalHtmlPath,
685 });
686 expect(yield* resolveAsset(token, "report.css")).toEqual({
687 kind: "file",
688 path: canonicalCssPath,
689 });
690 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
691 expect(yield* resolveAsset(token, ".env")).toBeNull();
692 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
693 }).pipe(Effect.provide(layerTest)),
694 );
695
696 it.effect("rejects workspace files outside the authorized root", () =>
697 Effect.gen(function* () {
698 const fileSystem = yield* FileSystem.FileSystem;
699 const path = yield* Path.Path;
700 const root = yield* fileSystem.makeTempDirectoryScoped({
701 prefix: "t3-asset-root-",
702 });
703 const outside = yield* fileSystem.makeTempDirectoryScoped({
704 prefix: "t3-asset-outside-",
705 });
706 const htmlPath = path.join(outside, "report.html");
707 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
708
709 const error = yield* issueAssetUrl({
710 resource: {
711 _tag: "workspace-file",
712 threadId: ThreadId.make("thread-1"),
713 path: htmlPath,
714 },
715 workspaceRoot: root,
716 }).pipe(Effect.flip);
717 expect(error.message).toBe("Workspace file path must be relative to the project root.");
718 expect(error).toMatchObject({
719 _tag: "AssetWorkspacePathValidationError",
720 resource: {
721 _tag: "workspace-file",
722 threadId: "thread-1",
723 path: htmlPath,
724 },
725 });
726 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
727 }).pipe(Effect.provide(layerTest)),
728 );
729
730 it.effect("previews workspace files with literal fragment characters in their paths", () =>
731 Effect.gen(function* () {
732 const fileSystem = yield* FileSystem.FileSystem;
733 const path = yield* Path.Path;
734 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
735 const directory = path.join(root, "assets#archive");
736 yield* fileSystem.makeDirectory(directory);
737
738 for (const name of ["icon#v2.png", "report#draft.pdf"]) {
739 const filePath = path.join(directory, name);
740 yield* fileSystem.writeFileString(filePath, "preview fixture");
741 const canonicalFile = yield* fileSystem.realPath(filePath);
742 const result = yield* issueAssetUrl({
743 resource: {
744 _tag: "workspace-file",
745 threadId: ThreadId.make("thread-1"),
746 path: filePath,
747 },
748 workspaceRoot: root,
749 });
750 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
751 const token = suffix.slice(0, suffix.indexOf("/"));
752
753 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
754 if (name.endsWith(".png")) {
755 expect(yield* resolveAsset(token, "other.png")).toBeNull();
756 }
757 }
758
759 const disguisedPath = path.join(root, "image.png#notes.txt");
760 yield* fileSystem.writeFileString(disguisedPath, "not an image");
761 const error = yield* issueAssetUrl({
762 resource: {
763 _tag: "workspace-file",
764 threadId: ThreadId.make("thread-1"),
765 path: disguisedPath,
766 },
767 workspaceRoot: root,
768 }).pipe(Effect.flip);
769 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
770 }).pipe(Effect.provide(layerTest)),
771 );
772
773 it.effect("signs MCP render intent only for inline HTML attachments", () =>
774 Effect.gen(function* () {
775 const config = yield* ServerConfig.ServerConfig;
776 const fs = yield* FileSystem.FileSystem;
777 const path = yield* Path.Path;
778 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
779 for (const extension of ["html", "pdf"]) {
780 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
781 yield* fs.writeFileString(
782 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
783 "capture",
784 );
785 for (const disposition of ["inline", "attachment"] as const) {
786 const result = yield* issueAssetUrl({
787 resource: {
788 _tag: "attachment",
789 attachmentId,
790 disposition,
791 renderIntent: "mcp-app",
792 },
793 });
794 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
795 const separator = suffix.indexOf("/");
796 const asset = yield* resolveAsset(
797 suffix.slice(0, separator),
798 suffix.slice(separator + 1),
799 );
800 if (asset?.kind !== "file") throw new Error("Expected attachment file");
801 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
802 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
803 );
804 const token = suffix.slice(0, separator);
805 const [payload, signature] = token.split(".");
806 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
807 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
808 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
809 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
810 }
811 }
812 }).pipe(Effect.provide(layerTest)),
813 );
814
815 it.effect("keeps inline requests for other attachment types as downloads", () =>
816 Effect.gen(function* () {
817 const config = yield* ServerConfig.ServerConfig;
818 const fileSystem = yield* FileSystem.FileSystem;
819 const path = yield* Path.Path;
820 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";
821 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);
822 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
823 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
824
825 const result = yield* issueAssetUrl({
826 resource: {
827 _tag: "attachment",
828 attachmentId,
829 fileName: "archive.zip",
830 mimeType: "text/html",
831 disposition: "inline",
832 },
833 });
834 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
835 const separatorIndex = suffix.indexOf("/");
836
837 expect(
838 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
839 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
840 }).pipe(Effect.provide(layerTest)),
841 );
842 it.effect("issues project favicon capabilities with a signed fallback", () =>
843 Effect.gen(function* () {
844 const fileSystem = yield* FileSystem.FileSystem;
845 const path = yield* Path.Path;
846 const root = yield* fileSystem.makeTempDirectoryScoped({
847 prefix: "t3-asset-favicon-",
848 });
849 const faviconPath = path.join(root, "favicon.svg");
850 const initialFavicon = "<svg>a</svg>";
851 const updatedFavicon = "<svg>b</svg>";
852 expect(updatedFavicon).toHaveLength(initialFavicon.length);
853 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
854 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
855
856 const faviconResult = yield* issueAssetUrl({
857 resource: { _tag: "project-favicon", cwd: root },
858 });
859 expect(faviconResult.sourcePath).toBe("favicon.svg");
860 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
861 expect(
862 yield* issueAssetUrl({
863 resource: { _tag: "project-favicon", cwd: root },
864 }),
865 ).toEqual(faviconResult);
866 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
867 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
868 expect(
869 yield* resolveAsset(
870 faviconSuffix.slice(0, faviconSeparatorIndex),
871 faviconSuffix.slice(faviconSeparatorIndex + 1),
872 ),
873 ).toEqual({ kind: "file", path: canonicalFaviconPath });
874
875 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
876 const updatedFaviconResult = yield* issueAssetUrl({
877 resource: { _tag: "project-favicon", cwd: root },
878 });
879 expect(
880 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
881 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
882
883 yield* fileSystem.remove(faviconPath);
884 const fallbackResult = yield* issueAssetUrl({
885 resource: { _tag: "project-favicon", cwd: root },
886 });
887 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
888 expect(fallbackResult.sourcePath).toBeUndefined();
889 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
890 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
891 expect(
892 yield* resolveAsset(
893 fallbackSuffix.slice(0, fallbackSeparatorIndex),
894 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
895 ),
896 ).toBeNull();
897 }).pipe(Effect.provide(layerTest)),
898 );
899
900 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
901 Effect.gen(function* () {
902 const fileSystem = yield* FileSystem.FileSystem;
903 const path = yield* Path.Path;
904 const root = yield* fileSystem.makeTempDirectoryScoped({
905 prefix: "t3-asset-favicon-workspace-",
906 });
907 const pictures = yield* fileSystem.makeTempDirectoryScoped({
908 prefix: "t3-asset-favicon-pictures-",
909 });
910 const externalPath = path.join(pictures, "custom.png");
911 const siblingPath = path.join(pictures, "sibling.png");
912 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
913 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
914 const canonicalPath = yield* fileSystem.realPath(externalPath);
915 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
916
917 const result = yield* issueAssetUrl({
918 resource: { _tag: "project-favicon", cwd: root },
919 projectFaviconPath: externalPath,
920 });
921 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
922 const separatorIndex = suffix.indexOf("/");
923
924 expect(result.sourcePath).toBe(externalPath);
925 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
926 expect(
927 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
928 ).toEqual({ kind: "file", path: canonicalPath });
929 const tamperedSuffixResult = yield* resolveAsset(
930 suffix.slice(0, separatorIndex),
931 "sibling.png",
932 );
933 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
934 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
935 }).pipe(Effect.provide(layerTest)),
936 );
937
938 it.effect("ignores a client favicon path hint", () =>
939 Effect.gen(function* () {
940 const fileSystem = yield* FileSystem.FileSystem;
941 const path = yield* Path.Path;
942 const root = yield* fileSystem.makeTempDirectoryScoped({
943 prefix: "t3-asset-favicon-hint-",
944 });
945 yield* fileSystem.makeDirectory(path.join(root, "brand"));
946 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
947 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
948
949 const result = yield* issueAssetUrl({
950 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
951 projectFaviconPath: "brand/saved.svg",
952 });
953
954 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
955 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
956 }).pipe(Effect.provide(layerTest)),
957 );
958
959 it.effect("serves GitHub-hosted pull request media through the repository's credential", () =>
960 Effect.gen(function* () {
961 const resolve = (relativeUrl: string) => {
962 const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
963 const separator = suffix.indexOf("/");
964 return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
965 };
966 const issue = (url: string) =>
967 issueAssetUrl({ resource: { _tag: "github-media", cwd: "/repo", url } });
968
969 const attachment = yield* issue(
970 "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
971 );
972 expect(attachment.relativeUrl.endsWith("/1a1842fb-6383-492f-873c-57aa0033fa6c")).toBe(true);
973 expect(yield* resolve(attachment.relativeUrl)).toEqual({
974 kind: "github-media",
975 url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
976 cwd: "/repo",
977 expiresAt: attachment.expiresAt,
978 });
979
980 const committed = yield* issue("https://github.com/owner/repo/blob/main/docs/shot.png");
981 expect(yield* resolve(committed.relativeUrl)).toMatchObject({
982 url: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",
983 });
984
985 const legacy = yield* issue("https://github.com/owner/repo/assets/45952064/1a1842fb");
986 expect(yield* resolve(legacy.relativeUrl)).toMatchObject({
987 url: "https://github.com/owner/repo/assets/45952064/1a1842fb",
988 });
989 const lfs = yield* issue("https://media.githubusercontent.com/media/owner/repo/main/a.mp4");
990 expect(yield* resolve(lfs.relativeUrl)).toMatchObject({
991 url: "https://media.githubusercontent.com/media/owner/repo/main/a.mp4",
992 });
993 const awkward = yield* issue("https://raw.githubusercontent.com/o/r/main/100%.png");
994 expect(awkward.relativeUrl.endsWith("/100%25.png")).toBe(true);
995
996 for (const url of [
997 "https://example.com/shot.png",
998 "https://example.com/shot.png?token=private-media-token",
999 "http://github.com/user-attachments/assets/1a1842fb",
1000 "https://github.com/owner/repo/pull/1",
1001 "https://github.com/owner/repo/blob/main/",
1002 ]) {
1003 const error = yield* issue(url).pipe(Effect.flip);
1004 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1005 const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1006 expect(encoded).not.toContain(url);
1007 }
1008 }).pipe(Effect.provide(layerTest)),
1009 );
1010});