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 AssetCreateUrlInput,
8 AssetPreviewTypeValidationError,
9 SOURCE_CONTROL_MEDIA_ASSET,
10 ThreadId,
11 TurnItemId,
12} from "@t3tools/contracts";
13import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
14import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
15import { describe, expect, it } from "@effect/vitest";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Path from "effect/Path";
21import * as PlatformError from "effect/PlatformError";
22import * as Schema from "effect/Schema";
23import * as TestClock from "effect/testing/TestClock";
24import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effect/http";
25import { vi } from "vite-plus/test";
26
27import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
28import * as ServerConfig from "../config.ts";
29import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
30import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
31import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
32import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
33import { assetFileResponse } from "../http.ts";
34import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
35import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
36import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
37import { fakeSourceControlDriverInstance } from "@t3tools/source-control-testing/fakeSourceControlDriver";
38import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
39import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
40import { sourceControlMediaResponse } from "./sourceControlMediaResponse.ts";
41import * as HostProcess from "@t3tools/shared/HostProcess";
42
43vi.mock("node:fs/promises", async (importOriginal) => {
44 const actual = await importOriginal<typeof NodeFSP>();
45 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
46});
47
48const layerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
49 prefix: "t3-asset-access-test-",
50});
51const screenshotPng = new Uint8Array(24);
52screenshotPng.set([
53 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52,
54]);
55new DataView(screenshotPng.buffer).setUint32(16, 390);
56new DataView(screenshotPng.buffer).setUint32(20, 844);
57const screenshotItem = {
58 id: TurnItemId.make("tool-screenshot"),
59 type: "dynamic_tool" as const,
60 threadId: ThreadId.make("thread-1"),
61 runId: null,
62 nodeId: null,
63 providerThreadId: null,
64 providerTurnId: null,
65 nativeItemRef: null,
66 parentItemId: null,
67 ordinal: 1,
68 status: "completed" as const,
69 title: null,
70 toolName: "mcp__t3-code__device_screenshot",
71 input: { deviceId: "phone" },
72 output: {
73 content: [
74 {
75 type: "image",
76 source: {
77 type: "base64",
78 media_type: "image/png",
79 data: Buffer.from(screenshotPng).toString("base64"),
80 },
81 },
82 ],
83 },
84 startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),
85 completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
86 updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
87};
88
89const oversizedScreenshotItem = {
90 ...screenshotItem,
91 id: TurnItemId.make("tool-screenshot-oversized"),
92 output: {
93 content: [
94 {
95 type: "image",
96 source: { type: "base64", media_type: "image/png", data: "A".repeat(14 * 1024 * 1024) },
97 },
98 ],
99 },
100};
101
102const layerTest = Layer.mergeAll(
103 NodeHttpPlatform.layer,
104 Layer.mock(Orchestrator.OrchestratorV2)({
105 getTurnItem: ({ itemId }) =>
106 Effect.succeed(
107 itemId === screenshotItem.id
108 ? screenshotItem
109 : itemId === oversizedScreenshotItem.id
110 ? oversizedScreenshotItem
111 : null,
112 ),
113 }),
114 layerConfig,
115 WorkspacePaths.layer,
116 ProjectFaviconResolver.layer.pipe(
117 Layer.provide(WorkspacePaths.layer),
118 Layer.provide(T3ProjectFileLoader.layer),
119 ),
120 NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
121 ServerSecretStore.layer.pipe(Layer.provide(layerConfig)),
122).pipe(Layer.provideMerge(NodeServices.layer));
123
124describe("AssetAccess", () => {
125 describe("readMcpAppHtml", () => {
126 it.effect("accepts snapshots at the stored HTML byte limit", () =>
127 Effect.gen(function* () {
128 const fileSystem = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
131 const file = path.join(directory, "app.html");
132 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
133 yield* fileSystem.writeFile(file, new Uint8Array(limit).fill(120));
134
135 const bytes = yield* readMcpAppHtml(file);
136 expect(bytes?.byteLength).toBe(limit);
137 expect(bytes?.every((byte) => byte === 120)).toBe(true);
138 }).pipe(Effect.provide(NodeServices.layer)),
139 );
140
141 it.effect("rejects snapshots one byte past the limit and much larger files", () =>
142 Effect.gen(function* () {
143 const fileSystem = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
146 const file = path.join(directory, "app.html");
147 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
148 for (const size of [limit + 1, limit * 2]) {
149 yield* fileSystem.writeFile(file, new Uint8Array(size).fill(120));
150 expect(yield* readMcpAppHtml(file)).toBeNull();
151 }
152 }).pipe(Effect.provide(NodeServices.layer)),
153 );
154
155 it.effect("preserves UTF-8 bytes across stream chunks and accepts empty snapshots", () =>
156 Effect.gen(function* () {
157 const fileSystem = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
160 const file = path.join(directory, "app.html");
161 for (const html of ["", "<body>" + "☃".repeat(100_000) + "</body>"]) {
162 const expected = new TextEncoder().encode(html);
163 yield* fileSystem.writeFile(file, expected);
164 const bytes = yield* readMcpAppHtml(file);
165 expect(bytes?.byteLength).toBe(expected.byteLength);
166 expect(bytes && new TextDecoder().decode(bytes)).toBe(html);
167 }
168 }).pipe(Effect.provide(NodeServices.layer)),
169 );
170
171 // regression: #17026 apply host color scheme to saved MCP apps
172 it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
173 Effect.gen(function* () {
174 const fileSystem = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
177 const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
178 expect(error._tag).toBe("PlatformError");
179 expect(error.reason._tag).toBe("NotFound");
180 }).pipe(Effect.provide(NodeServices.layer)),
181 );
182 });
183
184 it.effect("serves an image a tool returned inline from the stored item", () =>
185 Effect.gen(function* () {
186 const resource = {
187 _tag: "tool-output-image" as const,
188 threadId: screenshotItem.threadId,
189 itemId: screenshotItem.id,
190 index: 0,
191 };
192 const result = yield* issueAssetUrl({ resource });
193 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
194 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
195 const separator = suffix.indexOf("/");
196 expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({
197 kind: "bytes",
198 mimeType: "image/png",
199 bytes: Buffer.from(screenshotPng),
200 });
201 const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(
202 Effect.flip,
203 );
204 expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");
205 const oversized = yield* issueAssetUrl({
206 resource: { ...resource, itemId: oversizedScreenshotItem.id },
207 }).pipe(Effect.flip);
208 expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");
209 }).pipe(Effect.provide(layerTest)),
210 );
211
212 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
217 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
218 for (const [name, mimeType] of [
219 ["screenshot.png", "image/png"],
220 ["recording.mp4", "video/mp4"],
221 ["recording.webm", "video/webm"],
222 ["report.html", "text/html"],
223 ["report.pdf", "application/pdf"],
224 ["notes.odt", "application/vnd.oasis.opendocument.text"],
225 ["budget.ods", "application/vnd.oasis.opendocument.spreadsheet"],
226 ["slides.odp", "application/vnd.oasis.opendocument.presentation"],
227 ["notes.rtf", "application/rtf"],
228 ["book.epub", "application/epub+zip"],
229 ["analysis.ipynb", "application/x-ipynb+json"],
230 ["tone.wav", "audio/wav"],
231 ["tone.webm-audio", "audio/webm"],
232 ["archive.zip", "application/zip"],
233 ["archive.jar", "application/java-archive"],
234 ["archive.tar", "application/x-tar"],
235 ["archive.gz", "application/gzip"],
236 ["archive.tgz", "application/gzip"],
237 ["data.sqlite", "application/vnd.sqlite3"],
238 ["data.sqlite3", "application/vnd.sqlite3"],
239 ["data.db", "application/vnd.sqlite3"],
240 ] as const) {
241 const filePath = path.join(outside, name);
242 yield* fs.writeFileString(filePath, "media");
243 const canonicalFile = yield* fs.realPath(filePath);
244 const result = yield* issueAssetUrl({
245 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
246 workspaceRoot: root,
247 });
248 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
249 const separator = suffix.indexOf("/");
250 const token = suffix.slice(0, separator);
251 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
252 kind: "file",
253 path: canonicalFile,
254 mimeType,
255 });
256 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
257 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
258 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
259 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
260 }
261 }).pipe(Effect.provide(layerTest)),
262 );
263
264 it.effect("downloads any linked file with the same exact-file identity checks as media", () =>
265 Effect.gen(function* () {
266 const fs = yield* FileSystem.FileSystem;
267 const path = yield* Path.Path;
268 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-root-" });
269 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-outside-" });
270 for (const name of [
271 "data.csv",
272 "report.docx",
273 "sheet.xlsx",
274 "slides.pptx",
275 "archive.zip",
276 "no-extension",
277 ]) {
278 for (const directory of [root, outside]) {
279 const filePath = path.join(directory, name);
280 yield* fs.writeFileString(filePath, "shared file bytes");
281 const resource = {
282 _tag: "media-file" as const,
283 threadId: ThreadId.make("thread-1"),
284 path: directory === root ? name : filePath,
285 disposition: "attachment" as const,
286 };
287 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
288 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
289 const separator = suffix.indexOf("/");
290 const token = suffix.slice(0, separator);
291 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
292 expect(asset).toMatchObject({
293 kind: "file",
294 download: true,
295 fileName: name,
296 mimeType: "application/octet-stream",
297 });
298 if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
299 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
300 expect(response.headers.get("content-disposition")).toContain("attachment;");
301 expect(response.headers.get("content-type")).toBe("application/octet-stream");
302 expect(yield* Effect.promise(() => response.text())).toBe("shared file bytes");
303 expect(yield* resolveAsset(token, "sibling.docx")).toBeNull();
304 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
305 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
306 yield* fs.rename(filePath, `${filePath}.original`);
307 yield* fs.writeFileString(filePath, "replacement bytes");
308 expect(yield* resolveAsset(token, name)).toBeNull();
309 }
310 }
311 const directoryError = yield* issueAssetUrl({
312 resource: {
313 _tag: "media-file",
314 threadId: ThreadId.make("thread-1"),
315 path: root,
316 disposition: "attachment",
317 },
318 }).pipe(Effect.flip);
319 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
320 }).pipe(Effect.provide(layerTest)),
321 );
322
323 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
328 const root = path.join(directory, "workspace");
329 yield* fs.makeDirectory(root);
330 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
331 const filePath = path.resolve(root, relativePath);
332 yield* fs.writeFileString(filePath, "media");
333 const result = yield* issueAssetUrl({
334 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
335 workspaceRoot: root,
336 });
337 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
338 const separator = suffix.indexOf("/");
339 expect(
340 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
341 ).toMatchObject({
342 kind: "file",
343 path: yield* fs.realPath(filePath),
344 });
345 }
346 }).pipe(Effect.provide(layerTest)),
347 );
348
349 it.effect("previews draft audio and video from relative workspace paths", () =>
350 Effect.gen(function* () {
351 const fs = yield* FileSystem.FileSystem;
352 const path = yield* Path.Path;
353 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
354 for (const [name, mimeType] of [
355 ["video.mp4", "video/mp4"],
356 ["audio.wav", "audio/wav"],
357 ] as const) {
358 const filePath = path.join(root, name);
359 yield* fs.writeFileString(filePath, "media bytes");
360 const result = yield* issueAssetUrl({
361 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
362 workspaceRoot: root,
363 });
364 expect(result.fileRevision).toEqual(expect.any(String));
365 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
366 const separator = suffix.indexOf("/");
367 const token = suffix.slice(0, separator);
368 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
369 expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
370 if (asset?.kind !== "file") throw new Error("Expected draft media file");
371 for (const [range, status, body] of [
372 [undefined, 200, "media bytes"],
373 ["bytes=2-5", 206, "dia "],
374 ] as const) {
375 const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
376 if (resolved?.kind !== "file") throw new Error("Expected draft media file");
377 const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
378 expect(response.status).toBe(status);
379 expect(response.headers.get("content-type")).toBe(mimeType);
380 expect(response.headers.get("content-length")).toBe(String(body.length));
381 if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
382 expect(yield* Effect.promise(() => response.text())).toBe(body);
383 }
384 for (const requestedPath of [
385 name === "video.mp4" ? "audio.wav" : "video.mp4",
386 `../${name}`,
387 ]) {
388 expect(yield* resolveAsset(token, requestedPath)).toBeNull();
389 }
390 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
391 }
392 }).pipe(Effect.provide(layerTest)),
393 );
394
395 it.effect(
396 "rejects draft media escapes and disallowed types without enabling non-draft media",
397 () =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const path = yield* Path.Path;
401 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
402 const root = path.join(directory, "workspace");
403 yield* fs.makeDirectory(root);
404 for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
405 yield* fs.writeFileString(path.join(root, name), "workspace bytes");
406 yield* fs.writeFileString(path.join(directory, name), "outside bytes");
407 }
408 for (const [requestedPath, tag] of [
409 ["../video.mp4", "AssetWorkspacePathValidationError"],
410 ["../audio.wav", "AssetWorkspacePathValidationError"],
411 ["secret.txt", "AssetPreviewTypeValidationError"],
412 ] as const) {
413 const error = yield* issueAssetUrl({
414 resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
415 workspaceRoot: root,
416 }).pipe(Effect.flip);
417 expect(error._tag).toBe(tag);
418 }
419 for (const name of ["video.mp4", "audio.wav"]) {
420 const error = yield* issueAssetUrl({
421 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
422 workspaceRoot: root,
423 }).pipe(Effect.flip);
424 expect(error._tag).toBe("AssetPreviewTypeValidationError");
425 }
426 }).pipe(Effect.provide(layerTest)),
427 );
428
429 it.effect.skipIf(!symlinksSupported)(
430 "rejects draft media symlinks escaping the workspace or targeting disallowed types",
431 () =>
432 Effect.gen(function* () {
433 const fs = yield* FileSystem.FileSystem;
434 const path = yield* Path.Path;
435 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
436 const root = path.join(directory, "workspace");
437 yield* fs.makeDirectory(root);
438 const outside = path.join(directory, "outside.mp4");
439 const secret = path.join(root, "secret.txt");
440 yield* fs.writeFileString(outside, "outside bytes");
441 yield* fs.writeFileString(secret, "private bytes");
442 for (const [name, target] of [
443 ["escape.mp4", outside],
444 ["disguised.wav", secret],
445 ] as const) {
446 yield* fs.symlink(target, path.join(root, name));
447 const error = yield* issueAssetUrl({
448 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
449 workspaceRoot: root,
450 }).pipe(Effect.flip);
451 expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
452 error._tag,
453 );
454 }
455 }).pipe(Effect.provide(layerTest)),
456 );
457
458 it.effect.skipIf(!symlinksSupported)(
459 "preserves absolute draft previews through stable symlinks",
460 () =>
461 Effect.gen(function* () {
462 const fs = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
465 for (const extension of ["png", "mp4", "wav"]) {
466 const target = path.join(root, `target.${extension}`);
467 const alias = path.join(root, `alias.${extension}`);
468 yield* fs.writeFileString(target, "preview bytes");
469 yield* fs.symlink(target, alias);
470 const result = yield* issueAssetUrl({
471 resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
472 workspaceRoot: root,
473 });
474 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
475 const separator = suffix.indexOf("/");
476 expect(
477 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
478 ).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
479 }
480 }).pipe(Effect.provide(layerTest)),
481 );
482
483 it.effect.skipIf(!symlinksSupported)(
484 "rejects a draft media path swapped after workspace containment validation",
485 () =>
486 Effect.gen(function* () {
487 const fs = yield* FileSystem.FileSystem;
488 const path = yield* Path.Path;
489 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
490 const root = path.join(directory, "workspace");
491 yield* fs.makeDirectory(root);
492 const filePath = path.join(root, "video.mp4");
493 const outside = path.join(directory, "outside.mp4");
494 yield* fs.writeFileString(filePath, "workspace video");
495 yield* fs.writeFileString(outside, "outside video");
496 const canonicalFile = yield* fs.realPath(filePath);
497 let swapped = false;
498 const swappingFileSystem = FileSystem.FileSystem.of({
499 ...fs,
500 stat: Effect.fn(function* (requestedPath) {
501 const info = yield* fs.stat(requestedPath);
502 if (requestedPath === canonicalFile && !swapped) {
503 swapped = true;
504 yield* fs.remove(filePath);
505 yield* fs.symlink(outside, filePath);
506 }
507 return info;
508 }),
509 });
510 const result = yield* issueAssetUrl({
511 resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
512 workspaceRoot: root,
513 }).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
514 expect(swapped).toBe(true);
515 expect(result).toMatchObject({
516 _tag: "Failure",
517 failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
518 });
519 }).pipe(Effect.provide(layerTest)),
520 );
521
522 it.effect("resolves home-relative media paths independently of the workspace", () =>
523 Effect.gen(function* () {
524 const fs = yield* FileSystem.FileSystem;
525 const path = yield* Path.Path;
526 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
527 const home = path.join(directory, "var", "home", "alice");
528 const filePath = path.join(home, "Downloads", "repro.mp4");
529 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
530 yield* fs.writeFileString(filePath, "recording bytes");
531 const canonicalFile = yield* fs.realPath(filePath);
532 yield* Effect.gen(function* () {
533 for (const workspaceRoot of [
534 path.join(home, "project"),
535 path.join(directory, "srv", "project"),
536 undefined,
537 ]) {
538 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
539 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
540 const result = yield* issueAssetUrl({
541 resource: {
542 _tag: "media-file",
543 threadId: ThreadId.make("thread-1"),
544 path: requestedPath,
545 },
546 ...(workspaceRoot ? { workspaceRoot } : {}),
547 });
548 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
549 const separator = suffix.indexOf("/");
550 const asset = yield* resolveAsset(
551 suffix.slice(0, separator),
552 suffix.slice(separator + 1),
553 );
554 expect(asset).toMatchObject({
555 kind: "file",
556 path: canonicalFile,
557 mimeType: "video/mp4",
558 });
559 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
560 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
561 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
562 }
563 }
564 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
565 }).pipe(Effect.provide(layerTest)),
566 );
567
568 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
569 // Windows user's NTLM credentials to attacker.test.
570 it.effect("never resolves a network media path outside the thread's project", () =>
571 Effect.gen(function* () {
572 const fs = yield* FileSystem.FileSystem;
573 const path = yield* Path.Path;
574 const resolved: Array<string> = [];
575 const recordingFileSystem = FileSystem.FileSystem.of({
576 ...fs,
577 realPath: (requestedPath) => {
578 resolved.push(requestedPath);
579 return Effect.fail(
580 PlatformError.systemError({
581 _tag: "NotFound",
582 module: "FileSystem",
583 method: "realPath",
584 pathOrDescriptor: requestedPath,
585 }),
586 );
587 },
588 });
589 const share = "//nas.test/share/project";
590 for (const resource of [
591 {
592 _tag: "media-file",
593 threadId: ThreadId.make("thread-1"),
594 path: "//attacker.test/s/a.png",
595 },
596 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
597 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
598 ] as const) {
599 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
600 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
601 Effect.flip,
602 );
603 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
604 }
605 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
606 }).pipe(Effect.provide(layerTest)),
607 );
608
609 it.effect.skipIf(!symlinksSupported)(
610 "rejects non-previewable files, disguised targets, and directories",
611 () =>
612 Effect.gen(function* () {
613 const fs = yield* FileSystem.FileSystem;
614 const path = yield* Path.Path;
615 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
616 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
617 const filePath = path.join(root, name);
618 yield* fs.writeFileString(filePath, "not media");
619 const error = yield* issueAssetUrl({
620 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
621 }).pipe(Effect.flip);
622 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
623 }
624 const disguisedPath = path.join(root, "disguised.png");
625 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
626 const disguisedError = yield* issueAssetUrl({
627 resource: {
628 _tag: "media-file",
629 threadId: ThreadId.make("thread-1"),
630 path: disguisedPath,
631 },
632 }).pipe(Effect.flip);
633 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
634 const directoryPath = path.join(root, "directory.png");
635 yield* fs.makeDirectory(directoryPath);
636 const directoryError = yield* issueAssetUrl({
637 resource: {
638 _tag: "media-file",
639 threadId: ThreadId.make("thread-1"),
640 path: directoryPath,
641 },
642 }).pipe(Effect.flip);
643 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
644 }).pipe(Effect.provide(layerTest)),
645 );
646
647 it.effect.skipIf(!symlinksSupported)(
648 "binds media URLs to the canonical target and rejects symlink substitution",
649 () =>
650 Effect.gen(function* () {
651 const fs = yield* FileSystem.FileSystem;
652 const path = yield* Path.Path;
653 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
654 const filePath = path.join(root, "actual.svg");
655 const aliasPath = path.join(root, "alias.png");
656 const replacementPath = path.join(root, "other.svg");
657 yield* fs.writeFileString(filePath, "<svg/>");
658 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
659 yield* fs.symlink(filePath, aliasPath);
660 const canonicalFile = yield* fs.realPath(filePath);
661 const result = yield* issueAssetUrl({
662 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
663 });
664 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
665 const separator = suffix.indexOf("/");
666 const token = suffix.slice(0, separator);
667 const name = suffix.slice(separator + 1);
668 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
669 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
670 yield* fs.remove(aliasPath);
671 yield* fs.symlink(replacementPath, aliasPath);
672 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
673 yield* fs.remove(filePath);
674 yield* fs.symlink(replacementPath, filePath);
675 expect(yield* resolveAsset(token, name)).toBeNull();
676 }).pipe(Effect.provide(layerTest)),
677 );
678
679 it.effect.skipIf(!symlinksSupported)(
680 "keeps full and partial responses bound to the file opened during resolution",
681 () =>
682 Effect.gen(function* () {
683 const fs = yield* FileSystem.FileSystem;
684 const path = yield* Path.Path;
685 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
686 const filePath = path.join(root, "recording.mp4");
687 const savedPath = path.join(root, "saved.mp4");
688 const secretPath = path.join(root, "secret.txt");
689 yield* fs.writeFileString(filePath, "0123456789");
690 yield* fs.writeFileString(secretPath, "private information");
691 const result = yield* issueAssetUrl({
692 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
693 });
694 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
695 const separator = suffix.indexOf("/");
696 for (const [range, expected, status] of [
697 [undefined, "0123456789", 200],
698 ["bytes=2-5", "2345", 206],
699 ] as const) {
700 const asset = yield* resolveAsset(
701 suffix.slice(0, separator),
702 suffix.slice(separator + 1),
703 );
704 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
705
706 yield* fs.rename(filePath, savedPath);
707 yield* fs.symlink(secretPath, filePath);
708 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
709 expect(response.status).toBe(status);
710 expect(response.headers.get("content-length")).toBe(String(expected.length));
711 expect(yield* Effect.promise(() => response.text())).toBe(expected);
712 yield* fs.remove(filePath);
713 yield* fs.rename(savedPath, filePath);
714 }
715 }).pipe(Effect.provide(layerTest)),
716 );
717
718 it.effect.skipIf(!symlinksSupported)(
719 "rejects a symlink swapped in after canonical validation but before open",
720 () =>
721 Effect.gen(function* () {
722 const fs = yield* FileSystem.FileSystem;
723 const path = yield* Path.Path;
724 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
725 const filePath = path.join(root, "recording.mp4");
726 const secretPath = path.join(root, "secret.txt");
727 yield* fs.writeFileString(filePath, "video");
728 yield* fs.writeFileString(secretPath, "secret");
729 const canonicalPath = yield* fs.realPath(filePath);
730 const result = yield* issueAssetUrl({
731 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
732 });
733 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
734 const separator = suffix.indexOf("/");
735 const swappingFileSystem = FileSystem.FileSystem.of({
736 ...fs,
737 stat: Effect.fn(function* (requestedPath) {
738 const info = yield* fs.stat(requestedPath);
739 if (requestedPath === canonicalPath) {
740 yield* fs.remove(filePath);
741 yield* fs.symlink(secretPath, filePath);
742 }
743 return info;
744 }),
745 });
746 expect(
747 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
748 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
749 ),
750 ).toBeNull();
751 }).pipe(Effect.provide(layerTest)),
752 );
753
754 it.effect.skipIf(!symlinksSupported)(
755 "rejects an ancestor symlink race even when canonical path rechecks would pass",
756 () =>
757 Effect.gen(function* () {
758 const fs = yield* FileSystem.FileSystem;
759 const path = yield* Path.Path;
760 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
761 const publicDirectory = path.join(root, "public");
762 const privateDirectory = path.join(root, "private");
763 yield* fs.makeDirectory(publicDirectory);
764 yield* fs.makeDirectory(privateDirectory);
765 const filePath = path.join(publicDirectory, "recording.mp4");
766 yield* fs.writeFileString(filePath, "public video");
767 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
768 const canonicalPath = yield* fs.realPath(filePath);
769 const result = yield* issueAssetUrl({
770 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
771 });
772 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
773 const separator = suffix.indexOf("/");
774 const native = yield* Effect.promise(() =>
775 vi.importActual<typeof NodeFSP>("node:fs/promises"),
776 );
777 const savedDirectory = path.join(root, "saved");
778 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
779 await native.unlink(publicDirectory);
780 await native.rename(savedDirectory, publicDirectory);
781 const canonical = await native.realpath(canonicalPath);
782 await native.rename(publicDirectory, savedDirectory);
783 await native.symlink(privateDirectory, publicDirectory, "junction");
784 return canonical;
785 });
786 yield* Effect.addFinalizer(() =>
787 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
788 );
789 const swappingFileSystem = FileSystem.FileSystem.of({
790 ...fs,
791 realPath: Effect.fn(function* (requestedPath) {
792 const canonical = yield* fs.realPath(requestedPath);
793 if (requestedPath === canonicalPath) {
794 yield* fs.rename(publicDirectory, savedDirectory);
795 yield* Effect.promise(() =>
796 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
797 );
798 }
799 return canonical;
800 }),
801 });
802 expect(
803 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
804 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
805 ),
806 ).toBeNull();
807 }).pipe(Effect.provide(layerTest)),
808 );
809
810 it.effect("versions media by file changes rather than by re-signing", () =>
811 Effect.gen(function* () {
812 const fs = yield* FileSystem.FileSystem;
813 const path = yield* Path.Path;
814 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-revision-" });
815 const filePath = path.join(root, "recording.mp4");
816 yield* fs.writeFileString(filePath, "original");
817 yield* Effect.promise(() => NodeFSP.utimes(filePath, 1_000, 1_000));
818 const input = {
819 resource: {
820 _tag: "media-file" as const,
821 threadId: ThreadId.make("thread-1"),
822 path: filePath,
823 },
824 };
825 const original = yield* issueAssetUrl(input);
826 expect(original.fileRevision).toEqual(expect.any(String));
827
828 yield* TestClock.adjust("1 minute");
829 const renewed = yield* issueAssetUrl(input);
830 expect(renewed.relativeUrl).not.toBe(original.relativeUrl);
831 expect(renewed.fileRevision).toBe(original.fileRevision);
832
833 yield* fs.writeFileString(filePath, "modified");
834 yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
835 const edited = yield* issueAssetUrl(input);
836 expect(edited.fileRevision).not.toBe(original.fileRevision);
837
838 const replacement = path.join(root, "replacement.mp4");
839 yield* fs.writeFileString(replacement, "modified");
840 yield* Effect.promise(() => NodeFSP.utimes(replacement, 2_000, 2_000));
841 yield* fs.rename(replacement, filePath);
842 const replaced = yield* issueAssetUrl(input);
843 expect(replaced.fileRevision).not.toBe(edited.fileRevision);
844 }).pipe(Effect.provide(layerTest)),
845 );
846
847 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
848 Effect.gen(function* () {
849 const fs = yield* FileSystem.FileSystem;
850 const path = yield* Path.Path;
851 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
852 const filePath = path.join(root, "recording.mp4");
853 yield* fs.writeFileString(filePath, "original");
854 const input = {
855 resource: {
856 _tag: "media-file" as const,
857 threadId: ThreadId.make("thread-1"),
858 path: filePath,
859 },
860 };
861 const original = yield* issueAssetUrl(input);
862 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
863 const separator = suffix.indexOf("/");
864 const token = suffix.slice(0, separator);
865 const name = suffix.slice(separator + 1);
866 yield* fs.writeFileString(filePath, "in-place edit");
867 const edited = yield* resolveAsset(token, name);
868 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
869 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
870 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
871
872 const replacement = path.join(root, "replacement.mp4");
873 yield* fs.writeFileString(replacement, "replacement");
874 yield* fs.rename(replacement, filePath);
875 expect(yield* resolveAsset(token, name)).toBeNull();
876
877 const renewed = yield* issueAssetUrl(input);
878 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
879 const renewedSeparator = renewedSuffix.indexOf("/");
880 const renewedAsset = yield* resolveAsset(
881 renewedSuffix.slice(0, renewedSeparator),
882 renewedSuffix.slice(renewedSeparator + 1),
883 );
884 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
885 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
886 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
887 yield* fs.remove(filePath);
888 expect(
889 yield* resolveAsset(
890 renewedSuffix.slice(0, renewedSeparator),
891 renewedSuffix.slice(renewedSeparator + 1),
892 ),
893 ).toBeNull();
894 }).pipe(Effect.provide(layerTest)),
895 );
896
897 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
898 Effect.gen(function* () {
899 const fileSystem = yield* FileSystem.FileSystem;
900 const path = yield* Path.Path;
901 const root = yield* fileSystem.makeTempDirectoryScoped({
902 prefix: "t3-asset-workspace-",
903 });
904 const htmlPath = path.join(root, "report.html");
905 const cssPath = path.join(root, "report.css");
906 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
907 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
908 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
909 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
910 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
911
912 const result = yield* issueAssetUrl({
913 resource: {
914 _tag: "workspace-file",
915 threadId: ThreadId.make("thread-1"),
916 path: htmlPath,
917 },
918 workspaceRoot: root,
919 });
920 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
921 const separatorIndex = suffix.indexOf("/");
922 const token = suffix.slice(0, separatorIndex);
923
924 expect(yield* resolveAsset(token, "report.html")).toEqual({
925 kind: "file",
926 path: canonicalHtmlPath,
927 });
928 expect(yield* resolveAsset(token, "report.css")).toEqual({
929 kind: "file",
930 path: canonicalCssPath,
931 });
932 for (const extension of ["otf", "ttf", "woff", "woff2"]) {
933 const fontName = `preview.${extension}`;
934 const fontPath = path.join(root, fontName);
935 yield* fileSystem.writeFileString(fontPath, "font bytes");
936 const canonicalFontPath = yield* fileSystem.realPath(fontPath);
937 for (const resource of [
938 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
939 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
940 ]) {
941 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
942 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
943 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({
944 kind: "file",
945 path: canonicalFontPath,
946 });
947 }
948 }
949 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
950 expect(yield* resolveAsset(token, ".env")).toBeNull();
951 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
952 for (const extension of [
953 "odt",
954 "ods",
955 "odp",
956 "rtf",
957 "epub",
958 "ipynb",
959 "zip",
960 "jar",
961 "tar",
962 "gz",
963 "tgz",
964 "sqlite",
965 "sqlite3",
966 "db",
967 "docx",
968 "xlsx",
969 "pptx",
970 "bmp",
971 "heic",
972 "tif",
973 "tiff",
974 "weba",
975 "mmd",
976 "mermaid",
977 ]) {
978 const siblingName = `private.${extension}`;
979 yield* fileSystem.writeFileString(path.join(root, siblingName), "private sibling");
980 for (const resource of [
981 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
982 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
983 ]) {
984 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
985 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
986 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), siblingName)).toBeNull();
987 }
988 }
989 }).pipe(Effect.provide(layerTest)),
990 );
991
992 it.effect("rejects workspace files outside the authorized root", () =>
993 Effect.gen(function* () {
994 const fileSystem = yield* FileSystem.FileSystem;
995 const path = yield* Path.Path;
996 const root = yield* fileSystem.makeTempDirectoryScoped({
997 prefix: "t3-asset-root-",
998 });
999 const outside = yield* fileSystem.makeTempDirectoryScoped({
1000 prefix: "t3-asset-outside-",
1001 });
1002 const htmlPath = path.join(outside, "report.html");
1003 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
1004
1005 const error = yield* issueAssetUrl({
1006 resource: {
1007 _tag: "workspace-file",
1008 threadId: ThreadId.make("thread-1"),
1009 path: htmlPath,
1010 },
1011 workspaceRoot: root,
1012 }).pipe(Effect.flip);
1013 expect(error.message).toBe("Workspace file path must be relative to the project root.");
1014 expect(error).toMatchObject({
1015 _tag: "AssetWorkspacePathValidationError",
1016 resource: {
1017 _tag: "workspace-file",
1018 threadId: "thread-1",
1019 path: htmlPath,
1020 },
1021 });
1022 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
1023 }).pipe(Effect.provide(layerTest)),
1024 );
1025
1026 it.effect("issues exact workspace URLs for every non-HTML preview", () =>
1027 Effect.gen(function* () {
1028 const fileSystem = yield* FileSystem.FileSystem;
1029 const path = yield* Path.Path;
1030 const root = yield* fileSystem.makeTempDirectoryScoped({
1031 prefix: "t3-asset-image-workspace-",
1032 });
1033 const assetsDirectory = path.join(root, "assets");
1034 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
1035 yield* fileSystem.writeFileString(
1036 path.join(assetsDirectory, "private.docx"),
1037 "private document",
1038 );
1039 for (const extension of [
1040 "pdf",
1041 "odt",
1042 "ods",
1043 "odp",
1044 "rtf",
1045 "epub",
1046 "ipynb",
1047 "png",
1048 "bmp",
1049 "heic",
1050 "tif",
1051 "tiff",
1052 "docx",
1053 "xlsx",
1054 "pptx",
1055 "ttf",
1056 "otf",
1057 "woff",
1058 "woff2",
1059 "zip",
1060 "jar",
1061 "tar",
1062 "gz",
1063 "tgz",
1064 "sqlite",
1065 "sqlite3",
1066 "db",
1067 ]) {
1068 const name = `preview.${extension}`;
1069 const filePath = path.join(assetsDirectory, name);
1070 const siblingName = `other.${extension}`;
1071 yield* fileSystem.writeFileString(filePath, "preview");
1072 yield* fileSystem.writeFileString(
1073 path.join(assetsDirectory, siblingName),
1074 "private sibling",
1075 );
1076 const canonicalPath = yield* fileSystem.realPath(filePath);
1077 for (const resource of [
1078 {
1079 _tag: "workspace-file" as const,
1080 threadId: ThreadId.make("thread-1"),
1081 path: filePath,
1082 },
1083 { _tag: "draft-workspace-file" as const, cwd: root, path: `assets/${name}` },
1084 ]) {
1085 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
1086 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1087 const token = suffix.slice(0, suffix.indexOf("/"));
1088 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalPath });
1089 expect(yield* resolveAsset(token, siblingName)).toBeNull();
1090 expect(yield* resolveAsset(token, "private.docx")).toBeNull();
1091 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
1092 }
1093 }
1094 }).pipe(Effect.provide(layerTest)),
1095 );
1096
1097 it.effect("previews workspace files with literal fragment characters in their paths", () =>
1098 Effect.gen(function* () {
1099 const fileSystem = yield* FileSystem.FileSystem;
1100 const path = yield* Path.Path;
1101 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
1102 const directory = path.join(root, "assets#archive");
1103 yield* fileSystem.makeDirectory(directory);
1104
1105 for (const name of [
1106 "icon#v2.png",
1107 "report#draft.pdf",
1108 "report.docx",
1109 "workbook.xlsx",
1110 "slides.pptx",
1111 "notes.odt",
1112 "budget.ods",
1113 "slides.odp",
1114 "notes.rtf",
1115 "book.epub",
1116 "analysis.ipynb",
1117 "specimen.ttf",
1118 "specimen.otf",
1119 "specimen.woff",
1120 "specimen.woff2",
1121 "image.bmp",
1122 "image.heic",
1123 "image.tif",
1124 "image.tiff",
1125 ]) {
1126 const filePath = path.join(directory, name);
1127 yield* fileSystem.writeFileString(filePath, "preview fixture");
1128 const canonicalFile = yield* fileSystem.realPath(filePath);
1129 const result = yield* issueAssetUrl({
1130 resource: {
1131 _tag: "workspace-file",
1132 threadId: ThreadId.make("thread-1"),
1133 path: filePath,
1134 },
1135 workspaceRoot: root,
1136 });
1137 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1138 const token = suffix.slice(0, suffix.indexOf("/"));
1139
1140 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
1141 if (name.endsWith(".png")) {
1142 expect(yield* resolveAsset(token, "other.png")).toBeNull();
1143 }
1144 }
1145
1146 const disguisedPath = path.join(root, "image.png#notes.txt");
1147 yield* fileSystem.writeFileString(disguisedPath, "not an image");
1148 const error = yield* issueAssetUrl({
1149 resource: {
1150 _tag: "workspace-file",
1151 threadId: ThreadId.make("thread-1"),
1152 path: disguisedPath,
1153 },
1154 workspaceRoot: root,
1155 }).pipe(Effect.flip);
1156 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
1157 }).pipe(Effect.provide(layerTest)),
1158 );
1159
1160 it.effect("signs MCP render intent only for inline HTML attachments", () =>
1161 Effect.gen(function* () {
1162 const config = yield* ServerConfig.ServerConfig;
1163 const fs = yield* FileSystem.FileSystem;
1164 const path = yield* Path.Path;
1165 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
1166 for (const extension of ["html", "pdf"]) {
1167 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
1168 yield* fs.writeFileString(
1169 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
1170 "capture",
1171 );
1172 for (const disposition of ["inline", "attachment"] as const) {
1173 const result = yield* issueAssetUrl({
1174 resource: {
1175 _tag: "attachment",
1176 attachmentId,
1177 disposition,
1178 renderIntent: "mcp-app",
1179 },
1180 });
1181 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1182 const separator = suffix.indexOf("/");
1183 const asset = yield* resolveAsset(
1184 suffix.slice(0, separator),
1185 suffix.slice(separator + 1),
1186 );
1187 if (asset?.kind !== "file") throw new Error("Expected attachment file");
1188 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
1189 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
1190 );
1191 const token = suffix.slice(0, separator);
1192 const [payload, signature] = token.split(".");
1193 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1194 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1195 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1196 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1197 }
1198 }
1199 }).pipe(Effect.provide(layerTest)),
1200 );
1201
1202 it.effect.skipIf(!symlinksSupported)(
1203 "reports image attachment dimensions when the attachments directory is a symlink",
1204 () =>
1205 Effect.gen(function* () {
1206 const config = yield* ServerConfig.ServerConfig;
1207 const fs = yield* FileSystem.FileSystem;
1208 const path = yield* Path.Path;
1209 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachments-link-" });
1210 const realAttachmentsDir = path.join(root, "real");
1211 const linkedAttachmentsDir = path.join(root, "linked");
1212 yield* fs.makeDirectory(realAttachmentsDir);
1213 yield* fs.symlink(realAttachmentsDir, linkedAttachmentsDir);
1214 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000041";
1215 yield* fs.writeFile(path.join(realAttachmentsDir, `${attachmentId}.png`), screenshotPng);
1216
1217 const result = yield* issueAssetUrl({
1218 resource: { _tag: "attachment", attachmentId },
1219 }).pipe(
1220 Effect.provideService(ServerConfig.ServerConfig, {
1221 ...config,
1222 attachmentsDir: linkedAttachmentsDir,
1223 }),
1224 );
1225 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
1226 }).pipe(Effect.provide(layerTest)),
1227 );
1228
1229 it.effect("serves document attachments inline when a viewer requests it", () =>
1230 Effect.gen(function* () {
1231 const config = yield* ServerConfig.ServerConfig;
1232 const fileSystem = yield* FileSystem.FileSystem;
1233 const path = yield* Path.Path;
1234 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1235 for (const [extension, mimeType] of [
1236 ["pdf", "application/pdf"],
1237 ["svg", "image/svg+xml"],
1238 ["bmp", "image/bmp"],
1239 ["ttf", "font/ttf"],
1240 ["otf", "font/otf"],
1241 ["woff", "font/woff"],
1242 ["woff2", "font/woff2"],
1243 ["weba", "audio/webm"],
1244 ["zip", "application/zip"],
1245 ["jar", "application/java-archive"],
1246 ["tar", "application/x-tar"],
1247 ["gz", "application/gzip"],
1248 ["tgz", "application/gzip"],
1249 ["sqlite", "application/vnd.sqlite3"],
1250 ["sqlite3", "application/vnd.sqlite3"],
1251 ["db", "application/vnd.sqlite3"],
1252 ] as const) {
1253 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
1254 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
1255 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1256
1257 const result = yield* issueAssetUrl({
1258 resource: {
1259 _tag: "attachment",
1260 attachmentId,
1261 fileName: `report.${extension}`,
1262 mimeType: "text/html",
1263 disposition: "inline",
1264 },
1265 });
1266 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1267 const separatorIndex = suffix.indexOf("/");
1268
1269 expect(
1270 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1271 ).toEqual({
1272 kind: "file",
1273 path: attachmentPath,
1274 fileName: `report.${extension}`,
1275 mimeType,
1276 });
1277 }
1278 }).pipe(Effect.provide(layerTest)),
1279 );
1280
1281 it.effect("keeps inline requests for other attachment types as downloads", () =>
1282 Effect.gen(function* () {
1283 const config = yield* ServerConfig.ServerConfig;
1284 const fileSystem = yield* FileSystem.FileSystem;
1285 const path = yield* Path.Path;
1286 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-7z";
1287 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.7z`);
1288 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1289 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1290
1291 const result = yield* issueAssetUrl({
1292 resource: {
1293 _tag: "attachment",
1294 attachmentId,
1295 fileName: "archive.7z",
1296 mimeType: "text/html",
1297 disposition: "inline",
1298 },
1299 });
1300 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1301 const separatorIndex = suffix.indexOf("/");
1302
1303 expect(
1304 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1305 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
1306 }).pipe(Effect.provide(layerTest)),
1307 );
1308 it.effect("issues project favicon capabilities with a signed fallback", () =>
1309 Effect.gen(function* () {
1310 const fileSystem = yield* FileSystem.FileSystem;
1311 const path = yield* Path.Path;
1312 const root = yield* fileSystem.makeTempDirectoryScoped({
1313 prefix: "t3-asset-favicon-",
1314 });
1315 const faviconPath = path.join(root, "favicon.svg");
1316 const initialFavicon = "<svg>a</svg>";
1317 const updatedFavicon = "<svg>b</svg>";
1318 expect(updatedFavicon).toHaveLength(initialFavicon.length);
1319 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
1320 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
1321
1322 const faviconResult = yield* issueAssetUrl({
1323 resource: { _tag: "project-favicon", cwd: root },
1324 });
1325 expect(faviconResult.sourcePath).toBe("favicon.svg");
1326 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1327 expect(
1328 yield* issueAssetUrl({
1329 resource: { _tag: "project-favicon", cwd: root },
1330 }),
1331 ).toEqual(faviconResult);
1332 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1333 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
1334 expect(
1335 yield* resolveAsset(
1336 faviconSuffix.slice(0, faviconSeparatorIndex),
1337 faviconSuffix.slice(faviconSeparatorIndex + 1),
1338 ),
1339 ).toEqual({ kind: "file", path: canonicalFaviconPath });
1340
1341 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
1342 const updatedFaviconResult = yield* issueAssetUrl({
1343 resource: { _tag: "project-favicon", cwd: root },
1344 });
1345 expect(
1346 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
1347 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
1348
1349 yield* fileSystem.remove(faviconPath);
1350 const fallbackResult = yield* issueAssetUrl({
1351 resource: { _tag: "project-favicon", cwd: root },
1352 });
1353 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
1354 expect(fallbackResult.sourcePath).toBeUndefined();
1355 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1356 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
1357 expect(
1358 yield* resolveAsset(
1359 fallbackSuffix.slice(0, fallbackSeparatorIndex),
1360 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
1361 ),
1362 ).toBeNull();
1363 }).pipe(Effect.provide(layerTest)),
1364 );
1365
1366 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
1367 Effect.gen(function* () {
1368 const fileSystem = yield* FileSystem.FileSystem;
1369 const path = yield* Path.Path;
1370 const root = yield* fileSystem.makeTempDirectoryScoped({
1371 prefix: "t3-asset-favicon-workspace-",
1372 });
1373 const pictures = yield* fileSystem.makeTempDirectoryScoped({
1374 prefix: "t3-asset-favicon-pictures-",
1375 });
1376 const externalPath = path.join(pictures, "custom.png");
1377 const siblingPath = path.join(pictures, "sibling.png");
1378 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
1379 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
1380 const canonicalPath = yield* fileSystem.realPath(externalPath);
1381 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
1382
1383 const result = yield* issueAssetUrl({
1384 resource: { _tag: "project-favicon", cwd: root },
1385 projectFaviconPath: externalPath,
1386 });
1387 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1388 const separatorIndex = suffix.indexOf("/");
1389
1390 expect(result.sourcePath).toBe(externalPath);
1391 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
1392 expect(
1393 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1394 ).toEqual({ kind: "file", path: canonicalPath });
1395 const tamperedSuffixResult = yield* resolveAsset(
1396 suffix.slice(0, separatorIndex),
1397 "sibling.png",
1398 );
1399 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
1400 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
1401 }).pipe(Effect.provide(layerTest)),
1402 );
1403
1404 it.effect("ignores a client favicon path hint", () =>
1405 Effect.gen(function* () {
1406 const fileSystem = yield* FileSystem.FileSystem;
1407 const path = yield* Path.Path;
1408 const root = yield* fileSystem.makeTempDirectoryScoped({
1409 prefix: "t3-asset-favicon-hint-",
1410 });
1411 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1412 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
1413 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1414
1415 const result = yield* issueAssetUrl({
1416 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
1417 projectFaviconPath: "brand/saved.svg",
1418 });
1419
1420 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
1421 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
1422 }).pipe(Effect.provide(layerTest)),
1423 );
1424
1425 it.effect("serves a host's credentialed media through that host's driver", () => {
1426 const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
1427 const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
1428 const media = sourceControlDefinitions.mediaUrl(url)!;
1429 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
1430 {
1431 driver: { kind: media.definition.kind, definition: media.definition },
1432 instance: fakeSourceControlDriverInstance(media.definition.kind, {
1433 pullRequests: null,
1434 fetchMedia: (request) =>
1435 Effect.sync(() => {
1436 fetched.push(request);
1437 return HttpClientResponse.fromWeb(
1438 HttpClientRequest.get(request.url),
1439 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
1440 );
1441 }),
1442 }),
1443 },
1444 ]);
1445 return Effect.gen(function* () {
1446 const decodeAssetCreateUrlInput = Schema.decodeEffect(AssetCreateUrlInput);
1447
1448 // Every client and server release spells the resource this way on the wire.
1449 const { resource } = yield* decodeAssetCreateUrlInput({
1450 resource: { _tag: "github-media", cwd: "/repo", url },
1451 });
1452 const issued = yield* issueAssetUrl({ resource });
1453 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1454 const separator = suffix.indexOf("/");
1455 const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1456 expect(asset).toEqual({
1457 kind: "source-control-media",
1458 url: media.fetchUrl,
1459 cwd: "/repo",
1460 expiresAt: issued.expiresAt,
1461 });
1462 if (asset?.kind !== "source-control-media") return;
1463
1464 const response = yield* sourceControlMediaResponse(asset, {
1465 range: "bytes=0-4",
1466 cookie: "session",
1467 });
1468 expect(fetched).toEqual([{ url: media.fetchUrl, headers: { range: "bytes=0-4" } }]);
1469 expect(response.status).toBe(206);
1470 // The upstream sent no type, so it comes from the file name the host gave the media.
1471 expect(response.headers["content-type"]).toBe("image/png");
1472 expect(response.headers["content-length"]).toBe("5");
1473 }).pipe(Effect.provide(Layer.merge(layerTest, layerDrivers)), Effect.scoped);
1474 });
1475
1476 it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
1477 Effect.gen(function* () {
1478 const encodeAssetAccessError = Schema.encodeEffect(Schema.fromJsonString(AssetAccessError));
1479
1480 for (const url of [
1481 "https://example.com/shot.png",
1482 "https://example.com/shot.png?token=private-media-token",
1483 ]) {
1484 const error = yield* issueAssetUrl({
1485 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
1486 }).pipe(Effect.flip);
1487 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1488 const encoded = yield* encodeAssetAccessError(error);
1489 expect(encoded).not.toContain(url);
1490 }
1491 }).pipe(Effect.provide(layerTest)),
1492 );
1493});