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