Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.test.ts

1,289 lines56.2 KB

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 ["tone.wav", "audio/wav"],
225 ["tone.webm-audio", "audio/webm"],
226 ] as const) {
227 const filePath = path.join(outside, name);
228 yield* fs.writeFileString(filePath, "media");
229 const canonicalFile = yield* fs.realPath(filePath);
230 const result = yield* issueAssetUrl({
231 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
232 workspaceRoot: root,
233 });
234 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
235 const separator = suffix.indexOf("/");
236 const token = suffix.slice(0, separator);
237 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
238 kind: "file",
239 path: canonicalFile,
240 mimeType,
241 });
242 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
243 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
244 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
245 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
246 }
247 }).pipe(Effect.provide(layerTest)),
248 );
249​
250 it.effect("downloads any linked file with the same exact-file identity checks as media", () =>
251 Effect.gen(function* () {
252 const fs = yield* FileSystem.FileSystem;
253 const path = yield* Path.Path;
254 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-root-" });
255 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-outside-" });
256 for (const name of [
257 "data.csv",
258 "report.docx",
259 "sheet.xlsx",
260 "slides.pptx",
261 "archive.zip",
262 "no-extension",
263 ]) {
264 for (const directory of [root, outside]) {
265 const filePath = path.join(directory, name);
266 yield* fs.writeFileString(filePath, "shared file bytes");
267 const resource = {
268 _tag: "media-file" as const,
269 threadId: ThreadId.make("thread-1"),
270 path: directory === root ? name : filePath,
271 disposition: "attachment" as const,
272 };
273 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
274 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
275 const separator = suffix.indexOf("/");
276 const token = suffix.slice(0, separator);
277 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
278 expect(asset).toMatchObject({
279 kind: "file",
280 download: true,
281 fileName: name,
282 mimeType: "application/octet-stream",
283 });
284 if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
285 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
286 expect(response.headers.get("content-disposition")).toContain("attachment;");
287 expect(response.headers.get("content-type")).toBe("application/octet-stream");
288 expect(yield* Effect.promise(() => response.text())).toBe("shared file bytes");
289 expect(yield* resolveAsset(token, "sibling.docx")).toBeNull();
290 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
291 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
292 yield* fs.rename(filePath, `${filePath}.original`);
293 yield* fs.writeFileString(filePath, "replacement bytes");
294 expect(yield* resolveAsset(token, name)).toBeNull();
295 }
296 }
297 const directoryError = yield* issueAssetUrl({
298 resource: {
299 _tag: "media-file",
300 threadId: ThreadId.make("thread-1"),
301 path: root,
302 disposition: "attachment",
303 },
304 }).pipe(Effect.flip);
305 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
306 }).pipe(Effect.provide(layerTest)),
307 );
308​
309 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
310 Effect.gen(function* () {
311 const fs = yield* FileSystem.FileSystem;
312 const path = yield* Path.Path;
313 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
314 const root = path.join(directory, "workspace");
315 yield* fs.makeDirectory(root);
316 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
317 const filePath = path.resolve(root, relativePath);
318 yield* fs.writeFileString(filePath, "media");
319 const result = yield* issueAssetUrl({
320 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
321 workspaceRoot: root,
322 });
323 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
324 const separator = suffix.indexOf("/");
325 expect(
326 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
327 ).toMatchObject({
328 kind: "file",
329 path: yield* fs.realPath(filePath),
330 });
331 }
332 }).pipe(Effect.provide(layerTest)),
333 );
334​
335 it.effect("previews draft audio and video from relative workspace paths", () =>
336 Effect.gen(function* () {
337 const fs = yield* FileSystem.FileSystem;
338 const path = yield* Path.Path;
339 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
340 for (const [name, mimeType] of [
341 ["video.mp4", "video/mp4"],
342 ["audio.wav", "audio/wav"],
343 ] as const) {
344 const filePath = path.join(root, name);
345 yield* fs.writeFileString(filePath, "media bytes");
346 const result = yield* issueAssetUrl({
347 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
348 workspaceRoot: root,
349 });
350 expect(result.fileRevision).toEqual(expect.any(String));
351 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
352 const separator = suffix.indexOf("/");
353 const token = suffix.slice(0, separator);
354 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
355 expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
356 if (asset?.kind !== "file") throw new Error("Expected draft media file");
357 for (const [range, status, body] of [
358 [undefined, 200, "media bytes"],
359 ["bytes=2-5", 206, "dia "],
360 ] as const) {
361 const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
362 if (resolved?.kind !== "file") throw new Error("Expected draft media file");
363 const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
364 expect(response.status).toBe(status);
365 expect(response.headers.get("content-type")).toBe(mimeType);
366 expect(response.headers.get("content-length")).toBe(String(body.length));
367 if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
368 expect(yield* Effect.promise(() => response.text())).toBe(body);
369 }
370 for (const requestedPath of [
371 name === "video.mp4" ? "audio.wav" : "video.mp4",
372 `../${name}`,
373 ]) {
374 expect(yield* resolveAsset(token, requestedPath)).toBeNull();
375 }
376 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
377 }
378 }).pipe(Effect.provide(layerTest)),
379 );
380​
381 it.effect(
382 "rejects draft media escapes and disallowed types without enabling non-draft media",
383 () =>
384 Effect.gen(function* () {
385 const fs = yield* FileSystem.FileSystem;
386 const path = yield* Path.Path;
387 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
388 const root = path.join(directory, "workspace");
389 yield* fs.makeDirectory(root);
390 for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
391 yield* fs.writeFileString(path.join(root, name), "workspace bytes");
392 yield* fs.writeFileString(path.join(directory, name), "outside bytes");
393 }
394 for (const [requestedPath, tag] of [
395 ["../video.mp4", "AssetWorkspacePathValidationError"],
396 ["../audio.wav", "AssetWorkspacePathValidationError"],
397 ["secret.txt", "AssetPreviewTypeValidationError"],
398 ] as const) {
399 const error = yield* issueAssetUrl({
400 resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
401 workspaceRoot: root,
402 }).pipe(Effect.flip);
403 expect(error._tag).toBe(tag);
404 }
405 for (const name of ["video.mp4", "audio.wav"]) {
406 const error = yield* issueAssetUrl({
407 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
408 workspaceRoot: root,
409 }).pipe(Effect.flip);
410 expect(error._tag).toBe("AssetPreviewTypeValidationError");
411 }
412 }).pipe(Effect.provide(layerTest)),
413 );
414​
415 it.effect.skipIf(!symlinksSupported)(
416 "rejects draft media symlinks escaping the workspace or targeting disallowed types",
417 () =>
418 Effect.gen(function* () {
419 const fs = yield* FileSystem.FileSystem;
420 const path = yield* Path.Path;
421 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
422 const root = path.join(directory, "workspace");
423 yield* fs.makeDirectory(root);
424 const outside = path.join(directory, "outside.mp4");
425 const secret = path.join(root, "secret.txt");
426 yield* fs.writeFileString(outside, "outside bytes");
427 yield* fs.writeFileString(secret, "private bytes");
428 for (const [name, target] of [
429 ["escape.mp4", outside],
430 ["disguised.wav", secret],
431 ] as const) {
432 yield* fs.symlink(target, path.join(root, name));
433 const error = yield* issueAssetUrl({
434 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
435 workspaceRoot: root,
436 }).pipe(Effect.flip);
437 expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
438 error._tag,
439 );
440 }
441 }).pipe(Effect.provide(layerTest)),
442 );
443​
444 it.effect.skipIf(!symlinksSupported)(
445 "preserves absolute draft previews through stable symlinks",
446 () =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
451 for (const extension of ["png", "mp4", "wav"]) {
452 const target = path.join(root, `target.${extension}`);
453 const alias = path.join(root, `alias.${extension}`);
454 yield* fs.writeFileString(target, "preview bytes");
455 yield* fs.symlink(target, alias);
456 const result = yield* issueAssetUrl({
457 resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
458 workspaceRoot: root,
459 });
460 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
461 const separator = suffix.indexOf("/");
462 expect(
463 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
464 ).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
465 }
466 }).pipe(Effect.provide(layerTest)),
467 );
468​
469 it.effect.skipIf(!symlinksSupported)(
470 "rejects a draft media path swapped after workspace containment validation",
471 () =>
472 Effect.gen(function* () {
473 const fs = yield* FileSystem.FileSystem;
474 const path = yield* Path.Path;
475 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
476 const root = path.join(directory, "workspace");
477 yield* fs.makeDirectory(root);
478 const filePath = path.join(root, "video.mp4");
479 const outside = path.join(directory, "outside.mp4");
480 yield* fs.writeFileString(filePath, "workspace video");
481 yield* fs.writeFileString(outside, "outside video");
482 const canonicalFile = yield* fs.realPath(filePath);
483 let swapped = false;
484 const swappingFileSystem = FileSystem.FileSystem.of({
485 ...fs,
486 stat: Effect.fn(function* (requestedPath) {
487 const info = yield* fs.stat(requestedPath);
488 if (requestedPath === canonicalFile && !swapped) {
489 swapped = true;
490 yield* fs.remove(filePath);
491 yield* fs.symlink(outside, filePath);
492 }
493 return info;
494 }),
495 });
496 const result = yield* issueAssetUrl({
497 resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
498 workspaceRoot: root,
499 }).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
500 expect(swapped).toBe(true);
501 expect(result).toMatchObject({
502 _tag: "Failure",
503 failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
504 });
505 }).pipe(Effect.provide(layerTest)),
506 );
507​
508 it.effect("resolves home-relative media paths independently of the workspace", () =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const path = yield* Path.Path;
512 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
513 const home = path.join(directory, "var", "home", "alice");
514 const filePath = path.join(home, "Downloads", "repro.mp4");
515 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
516 yield* fs.writeFileString(filePath, "recording bytes");
517 const canonicalFile = yield* fs.realPath(filePath);
518 yield* Effect.gen(function* () {
519 for (const workspaceRoot of [
520 path.join(home, "project"),
521 path.join(directory, "srv", "project"),
522 undefined,
523 ]) {
524 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
525 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
526 const result = yield* issueAssetUrl({
527 resource: {
528 _tag: "media-file",
529 threadId: ThreadId.make("thread-1"),
530 path: requestedPath,
531 },
532 ...(workspaceRoot ? { workspaceRoot } : {}),
533 });
534 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
535 const separator = suffix.indexOf("/");
536 const asset = yield* resolveAsset(
537 suffix.slice(0, separator),
538 suffix.slice(separator + 1),
539 );
540 expect(asset).toMatchObject({
541 kind: "file",
542 path: canonicalFile,
543 mimeType: "video/mp4",
544 });
545 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
546 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
547 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
548 }
549 }
550 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
551 }).pipe(Effect.provide(layerTest)),
552 );
553​
554 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
555 // Windows user's NTLM credentials to attacker.test.
556 it.effect("never resolves a network media path outside the thread's project", () =>
557 Effect.gen(function* () {
558 const fs = yield* FileSystem.FileSystem;
559 const path = yield* Path.Path;
560 const resolved: Array<string> = [];
561 const recordingFileSystem = FileSystem.FileSystem.of({
562 ...fs,
563 realPath: (requestedPath) => {
564 resolved.push(requestedPath);
565 return Effect.fail(
566 PlatformError.systemError({
567 _tag: "NotFound",
568 module: "FileSystem",
569 method: "realPath",
570 pathOrDescriptor: requestedPath,
571 }),
572 );
573 },
574 });
575 const share = "//nas.test/share/project";
576 for (const resource of [
577 {
578 _tag: "media-file",
579 threadId: ThreadId.make("thread-1"),
580 path: "//attacker.test/s/a.png",
581 },
582 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
583 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
584 ] as const) {
585 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
586 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
587 Effect.flip,
588 );
589 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
590 }
591 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
592 }).pipe(Effect.provide(layerTest)),
593 );
594​
595 it.effect.skipIf(!symlinksSupported)(
596 "rejects non-previewable files, disguised targets, and directories",
597 () =>
598 Effect.gen(function* () {
599 const fs = yield* FileSystem.FileSystem;
600 const path = yield* Path.Path;
601 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
602 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
603 const filePath = path.join(root, name);
604 yield* fs.writeFileString(filePath, "not media");
605 const error = yield* issueAssetUrl({
606 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
607 }).pipe(Effect.flip);
608 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
609 }
610 const disguisedPath = path.join(root, "disguised.png");
611 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
612 const disguisedError = yield* issueAssetUrl({
613 resource: {
614 _tag: "media-file",
615 threadId: ThreadId.make("thread-1"),
616 path: disguisedPath,
617 },
618 }).pipe(Effect.flip);
619 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
620 const directoryPath = path.join(root, "directory.png");
621 yield* fs.makeDirectory(directoryPath);
622 const directoryError = yield* issueAssetUrl({
623 resource: {
624 _tag: "media-file",
625 threadId: ThreadId.make("thread-1"),
626 path: directoryPath,
627 },
628 }).pipe(Effect.flip);
629 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
630 }).pipe(Effect.provide(layerTest)),
631 );
632​
633 it.effect.skipIf(!symlinksSupported)(
634 "binds media URLs to the canonical target and rejects symlink substitution",
635 () =>
636 Effect.gen(function* () {
637 const fs = yield* FileSystem.FileSystem;
638 const path = yield* Path.Path;
639 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
640 const filePath = path.join(root, "actual.svg");
641 const aliasPath = path.join(root, "alias.png");
642 const replacementPath = path.join(root, "other.svg");
643 yield* fs.writeFileString(filePath, "<svg/>");
644 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
645 yield* fs.symlink(filePath, aliasPath);
646 const canonicalFile = yield* fs.realPath(filePath);
647 const result = yield* issueAssetUrl({
648 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
649 });
650 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
651 const separator = suffix.indexOf("/");
652 const token = suffix.slice(0, separator);
653 const name = suffix.slice(separator + 1);
654 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
655 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
656 yield* fs.remove(aliasPath);
657 yield* fs.symlink(replacementPath, aliasPath);
658 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
659 yield* fs.remove(filePath);
660 yield* fs.symlink(replacementPath, filePath);
661 expect(yield* resolveAsset(token, name)).toBeNull();
662 }).pipe(Effect.provide(layerTest)),
663 );
664​
665 it.effect.skipIf(!symlinksSupported)(
666 "keeps full and partial responses bound to the file opened during resolution",
667 () =>
668 Effect.gen(function* () {
669 const fs = yield* FileSystem.FileSystem;
670 const path = yield* Path.Path;
671 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
672 const filePath = path.join(root, "recording.mp4");
673 const savedPath = path.join(root, "saved.mp4");
674 const secretPath = path.join(root, "secret.txt");
675 yield* fs.writeFileString(filePath, "0123456789");
676 yield* fs.writeFileString(secretPath, "private information");
677 const result = yield* issueAssetUrl({
678 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
679 });
680 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
681 const separator = suffix.indexOf("/");
682 for (const [range, expected, status] of [
683 [undefined, "0123456789", 200],
684 ["bytes=2-5", "2345", 206],
685 ] as const) {
686 const asset = yield* resolveAsset(
687 suffix.slice(0, separator),
688 suffix.slice(separator + 1),
689 );
690 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
691​
692 yield* fs.rename(filePath, savedPath);
693 yield* fs.symlink(secretPath, filePath);
694 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
695 expect(response.status).toBe(status);
696 expect(response.headers.get("content-length")).toBe(String(expected.length));
697 expect(yield* Effect.promise(() => response.text())).toBe(expected);
698 yield* fs.remove(filePath);
699 yield* fs.rename(savedPath, filePath);
700 }
701 }).pipe(Effect.provide(layerTest)),
702 );
703​
704 it.effect.skipIf(!symlinksSupported)(
705 "rejects a symlink swapped in after canonical validation but before open",
706 () =>
707 Effect.gen(function* () {
708 const fs = yield* FileSystem.FileSystem;
709 const path = yield* Path.Path;
710 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
711 const filePath = path.join(root, "recording.mp4");
712 const secretPath = path.join(root, "secret.txt");
713 yield* fs.writeFileString(filePath, "video");
714 yield* fs.writeFileString(secretPath, "secret");
715 const canonicalPath = yield* fs.realPath(filePath);
716 const result = yield* issueAssetUrl({
717 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
718 });
719 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
720 const separator = suffix.indexOf("/");
721 const swappingFileSystem = FileSystem.FileSystem.of({
722 ...fs,
723 stat: Effect.fn(function* (requestedPath) {
724 const info = yield* fs.stat(requestedPath);
725 if (requestedPath === canonicalPath) {
726 yield* fs.remove(filePath);
727 yield* fs.symlink(secretPath, filePath);
728 }
729 return info;
730 }),
731 });
732 expect(
733 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
734 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
735 ),
736 ).toBeNull();
737 }).pipe(Effect.provide(layerTest)),
738 );
739​
740 it.effect.skipIf(!symlinksSupported)(
741 "rejects an ancestor symlink race even when canonical path rechecks would pass",
742 () =>
743 Effect.gen(function* () {
744 const fs = yield* FileSystem.FileSystem;
745 const path = yield* Path.Path;
746 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
747 const publicDirectory = path.join(root, "public");
748 const privateDirectory = path.join(root, "private");
749 yield* fs.makeDirectory(publicDirectory);
750 yield* fs.makeDirectory(privateDirectory);
751 const filePath = path.join(publicDirectory, "recording.mp4");
752 yield* fs.writeFileString(filePath, "public video");
753 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
754 const canonicalPath = yield* fs.realPath(filePath);
755 const result = yield* issueAssetUrl({
756 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
757 });
758 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
759 const separator = suffix.indexOf("/");
760 const native = yield* Effect.promise(() =>
761 vi.importActual<typeof NodeFSP>("node:fs/promises"),
762 );
763 const savedDirectory = path.join(root, "saved");
764 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
765 await native.unlink(publicDirectory);
766 await native.rename(savedDirectory, publicDirectory);
767 const canonical = await native.realpath(canonicalPath);
768 await native.rename(publicDirectory, savedDirectory);
769 await native.symlink(privateDirectory, publicDirectory, "junction");
770 return canonical;
771 });
772 yield* Effect.addFinalizer(() =>
773 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
774 );
775 const swappingFileSystem = FileSystem.FileSystem.of({
776 ...fs,
777 realPath: Effect.fn(function* (requestedPath) {
778 const canonical = yield* fs.realPath(requestedPath);
779 if (requestedPath === canonicalPath) {
780 yield* fs.rename(publicDirectory, savedDirectory);
781 yield* Effect.promise(() =>
782 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
783 );
784 }
785 return canonical;
786 }),
787 });
788 expect(
789 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
790 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
791 ),
792 ).toBeNull();
793 }).pipe(Effect.provide(layerTest)),
794 );
795​
796 it.effect("versions media by file changes rather than by re-signing", () =>
797 Effect.gen(function* () {
798 const fs = yield* FileSystem.FileSystem;
799 const path = yield* Path.Path;
800 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-revision-" });
801 const filePath = path.join(root, "recording.mp4");
802 yield* fs.writeFileString(filePath, "original");
803 yield* Effect.promise(() => NodeFSP.utimes(filePath, 1_000, 1_000));
804 const input = {
805 resource: {
806 _tag: "media-file" as const,
807 threadId: ThreadId.make("thread-1"),
808 path: filePath,
809 },
810 };
811 const original = yield* issueAssetUrl(input);
812 expect(original.fileRevision).toEqual(expect.any(String));
813​
814 yield* TestClock.adjust("1 minute");
815 const renewed = yield* issueAssetUrl(input);
816 expect(renewed.relativeUrl).not.toBe(original.relativeUrl);
817 expect(renewed.fileRevision).toBe(original.fileRevision);
818​
819 yield* fs.writeFileString(filePath, "modified");
820 yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
821 const edited = yield* issueAssetUrl(input);
822 expect(edited.fileRevision).not.toBe(original.fileRevision);
823​
824 const replacement = path.join(root, "replacement.mp4");
825 yield* fs.writeFileString(replacement, "modified");
826 yield* Effect.promise(() => NodeFSP.utimes(replacement, 2_000, 2_000));
827 yield* fs.rename(replacement, filePath);
828 const replaced = yield* issueAssetUrl(input);
829 expect(replaced.fileRevision).not.toBe(edited.fileRevision);
830 }).pipe(Effect.provide(layerTest)),
831 );
832​
833 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
834 Effect.gen(function* () {
835 const fs = yield* FileSystem.FileSystem;
836 const path = yield* Path.Path;
837 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
838 const filePath = path.join(root, "recording.mp4");
839 yield* fs.writeFileString(filePath, "original");
840 const input = {
841 resource: {
842 _tag: "media-file" as const,
843 threadId: ThreadId.make("thread-1"),
844 path: filePath,
845 },
846 };
847 const original = yield* issueAssetUrl(input);
848 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
849 const separator = suffix.indexOf("/");
850 const token = suffix.slice(0, separator);
851 const name = suffix.slice(separator + 1);
852 yield* fs.writeFileString(filePath, "in-place edit");
853 const edited = yield* resolveAsset(token, name);
854 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
855 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
856 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
857​
858 const replacement = path.join(root, "replacement.mp4");
859 yield* fs.writeFileString(replacement, "replacement");
860 yield* fs.rename(replacement, filePath);
861 expect(yield* resolveAsset(token, name)).toBeNull();
862​
863 const renewed = yield* issueAssetUrl(input);
864 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
865 const renewedSeparator = renewedSuffix.indexOf("/");
866 const renewedAsset = yield* resolveAsset(
867 renewedSuffix.slice(0, renewedSeparator),
868 renewedSuffix.slice(renewedSeparator + 1),
869 );
870 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
871 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
872 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
873 yield* fs.remove(filePath);
874 expect(
875 yield* resolveAsset(
876 renewedSuffix.slice(0, renewedSeparator),
877 renewedSuffix.slice(renewedSeparator + 1),
878 ),
879 ).toBeNull();
880 }).pipe(Effect.provide(layerTest)),
881 );
882​
883 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
884 Effect.gen(function* () {
885 const fileSystem = yield* FileSystem.FileSystem;
886 const path = yield* Path.Path;
887 const root = yield* fileSystem.makeTempDirectoryScoped({
888 prefix: "t3-asset-workspace-",
889 });
890 const htmlPath = path.join(root, "report.html");
891 const cssPath = path.join(root, "report.css");
892 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
893 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
894 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
895 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
896 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
897​
898 const result = yield* issueAssetUrl({
899 resource: {
900 _tag: "workspace-file",
901 threadId: ThreadId.make("thread-1"),
902 path: htmlPath,
903 },
904 workspaceRoot: root,
905 });
906 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
907 const separatorIndex = suffix.indexOf("/");
908 const token = suffix.slice(0, separatorIndex);
909​
910 expect(yield* resolveAsset(token, "report.html")).toEqual({
911 kind: "file",
912 path: canonicalHtmlPath,
913 });
914 expect(yield* resolveAsset(token, "report.css")).toEqual({
915 kind: "file",
916 path: canonicalCssPath,
917 });
918 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
919 expect(yield* resolveAsset(token, ".env")).toBeNull();
920 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
921 }).pipe(Effect.provide(layerTest)),
922 );
923​
924 it.effect("rejects workspace files outside the authorized root", () =>
925 Effect.gen(function* () {
926 const fileSystem = yield* FileSystem.FileSystem;
927 const path = yield* Path.Path;
928 const root = yield* fileSystem.makeTempDirectoryScoped({
929 prefix: "t3-asset-root-",
930 });
931 const outside = yield* fileSystem.makeTempDirectoryScoped({
932 prefix: "t3-asset-outside-",
933 });
934 const htmlPath = path.join(outside, "report.html");
935 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
936​
937 const error = yield* issueAssetUrl({
938 resource: {
939 _tag: "workspace-file",
940 threadId: ThreadId.make("thread-1"),
941 path: htmlPath,
942 },
943 workspaceRoot: root,
944 }).pipe(Effect.flip);
945 expect(error.message).toBe("Workspace file path must be relative to the project root.");
946 expect(error).toMatchObject({
947 _tag: "AssetWorkspacePathValidationError",
948 resource: {
949 _tag: "workspace-file",
950 threadId: "thread-1",
951 path: htmlPath,
952 },
953 });
954 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
955 }).pipe(Effect.provide(layerTest)),
956 );
957​
958 it.effect("previews workspace files with literal fragment characters in their paths", () =>
959 Effect.gen(function* () {
960 const fileSystem = yield* FileSystem.FileSystem;
961 const path = yield* Path.Path;
962 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
963 const directory = path.join(root, "assets#archive");
964 yield* fileSystem.makeDirectory(directory);
965​
966 for (const name of ["icon#v2.png", "report#draft.pdf"]) {
967 const filePath = path.join(directory, name);
968 yield* fileSystem.writeFileString(filePath, "preview fixture");
969 const canonicalFile = yield* fileSystem.realPath(filePath);
970 const result = yield* issueAssetUrl({
971 resource: {
972 _tag: "workspace-file",
973 threadId: ThreadId.make("thread-1"),
974 path: filePath,
975 },
976 workspaceRoot: root,
977 });
978 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
979 const token = suffix.slice(0, suffix.indexOf("/"));
980​
981 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
982 if (name.endsWith(".png")) {
983 expect(yield* resolveAsset(token, "other.png")).toBeNull();
984 }
985 }
986​
987 const disguisedPath = path.join(root, "image.png#notes.txt");
988 yield* fileSystem.writeFileString(disguisedPath, "not an image");
989 const error = yield* issueAssetUrl({
990 resource: {
991 _tag: "workspace-file",
992 threadId: ThreadId.make("thread-1"),
993 path: disguisedPath,
994 },
995 workspaceRoot: root,
996 }).pipe(Effect.flip);
997 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
998 }).pipe(Effect.provide(layerTest)),
999 );
1000​
1001 it.effect("signs MCP render intent only for inline HTML attachments", () =>
1002 Effect.gen(function* () {
1003 const config = yield* ServerConfig.ServerConfig;
1004 const fs = yield* FileSystem.FileSystem;
1005 const path = yield* Path.Path;
1006 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
1007 for (const extension of ["html", "pdf"]) {
1008 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
1009 yield* fs.writeFileString(
1010 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
1011 "capture",
1012 );
1013 for (const disposition of ["inline", "attachment"] as const) {
1014 const result = yield* issueAssetUrl({
1015 resource: {
1016 _tag: "attachment",
1017 attachmentId,
1018 disposition,
1019 renderIntent: "mcp-app",
1020 },
1021 });
1022 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1023 const separator = suffix.indexOf("/");
1024 const asset = yield* resolveAsset(
1025 suffix.slice(0, separator),
1026 suffix.slice(separator + 1),
1027 );
1028 if (asset?.kind !== "file") throw new Error("Expected attachment file");
1029 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
1030 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
1031 );
1032 const token = suffix.slice(0, separator);
1033 const [payload, signature] = token.split(".");
1034 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1035 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1036 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1037 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1040 }).pipe(Effect.provide(layerTest)),
1041 );
1042​
1043 it.effect("serves document attachments inline when a viewer requests it", () =>
1044 Effect.gen(function* () {
1045 const config = yield* ServerConfig.ServerConfig;
1046 const fileSystem = yield* FileSystem.FileSystem;
1047 const path = yield* Path.Path;
1048 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1049 for (const [extension, mimeType] of [
1050 ["pdf", "application/pdf"],
1051 ["svg", "image/svg+xml"],
1052 ] as const) {
1053 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
1054 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
1055 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1056​
1057 const result = yield* issueAssetUrl({
1058 resource: {
1059 _tag: "attachment",
1060 attachmentId,
1061 fileName: `report.${extension}`,
1062 mimeType,
1063 disposition: "inline",
1064 },
1065 });
1066 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1067 const separatorIndex = suffix.indexOf("/");
1068​
1069 expect(
1070 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1071 ).toEqual({
1072 kind: "file",
1073 path: attachmentPath,
1074 fileName: `report.${extension}`,
1075 mimeType,
1076 });
1078 }).pipe(Effect.provide(layerTest)),
1079 );
1080​
1081 it.effect("keeps inline requests for other attachment types as downloads", () =>
1082 Effect.gen(function* () {
1083 const config = yield* ServerConfig.ServerConfig;
1084 const fileSystem = yield* FileSystem.FileSystem;
1085 const path = yield* Path.Path;
1086 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";
1087 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);
1088 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1089 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1090​
1091 const result = yield* issueAssetUrl({
1092 resource: {
1093 _tag: "attachment",
1094 attachmentId,
1095 fileName: "archive.zip",
1096 mimeType: "text/html",
1097 disposition: "inline",
1098 },
1099 });
1100 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1101 const separatorIndex = suffix.indexOf("/");
1102​
1103 expect(
1104 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1105 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
1106 }).pipe(Effect.provide(layerTest)),
1107 );
1108 it.effect("issues project favicon capabilities with a signed fallback", () =>
1109 Effect.gen(function* () {
1110 const fileSystem = yield* FileSystem.FileSystem;
1111 const path = yield* Path.Path;
1112 const root = yield* fileSystem.makeTempDirectoryScoped({
1113 prefix: "t3-asset-favicon-",
1114 });
1115 const faviconPath = path.join(root, "favicon.svg");
1116 const initialFavicon = "<svg>a</svg>";
1117 const updatedFavicon = "<svg>b</svg>";
1118 expect(updatedFavicon).toHaveLength(initialFavicon.length);
1119 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
1120 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
1121​
1122 const faviconResult = yield* issueAssetUrl({
1123 resource: { _tag: "project-favicon", cwd: root },
1124 });
1125 expect(faviconResult.sourcePath).toBe("favicon.svg");
1126 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1127 expect(
1128 yield* issueAssetUrl({
1129 resource: { _tag: "project-favicon", cwd: root },
1130 }),
1131 ).toEqual(faviconResult);
1132 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1133 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
1134 expect(
1135 yield* resolveAsset(
1136 faviconSuffix.slice(0, faviconSeparatorIndex),
1137 faviconSuffix.slice(faviconSeparatorIndex + 1),
1138 ),
1139 ).toEqual({ kind: "file", path: canonicalFaviconPath });
1140​
1141 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
1142 const updatedFaviconResult = yield* issueAssetUrl({
1143 resource: { _tag: "project-favicon", cwd: root },
1144 });
1145 expect(
1146 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
1147 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
1148​
1149 yield* fileSystem.remove(faviconPath);
1150 const fallbackResult = yield* issueAssetUrl({
1151 resource: { _tag: "project-favicon", cwd: root },
1152 });
1153 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
1154 expect(fallbackResult.sourcePath).toBeUndefined();
1155 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1156 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
1157 expect(
1158 yield* resolveAsset(
1159 fallbackSuffix.slice(0, fallbackSeparatorIndex),
1160 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
1161 ),
1162 ).toBeNull();
1163 }).pipe(Effect.provide(layerTest)),
1164 );
1165​
1166 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
1167 Effect.gen(function* () {
1168 const fileSystem = yield* FileSystem.FileSystem;
1169 const path = yield* Path.Path;
1170 const root = yield* fileSystem.makeTempDirectoryScoped({
1171 prefix: "t3-asset-favicon-workspace-",
1172 });
1173 const pictures = yield* fileSystem.makeTempDirectoryScoped({
1174 prefix: "t3-asset-favicon-pictures-",
1175 });
1176 const externalPath = path.join(pictures, "custom.png");
1177 const siblingPath = path.join(pictures, "sibling.png");
1178 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
1179 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
1180 const canonicalPath = yield* fileSystem.realPath(externalPath);
1181 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
1182​
1183 const result = yield* issueAssetUrl({
1184 resource: { _tag: "project-favicon", cwd: root },
1185 projectFaviconPath: externalPath,
1186 });
1187 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1188 const separatorIndex = suffix.indexOf("/");
1189​
1190 expect(result.sourcePath).toBe(externalPath);
1191 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
1192 expect(
1193 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1194 ).toEqual({ kind: "file", path: canonicalPath });
1195 const tamperedSuffixResult = yield* resolveAsset(
1196 suffix.slice(0, separatorIndex),
1197 "sibling.png",
1198 );
1199 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
1200 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
1201 }).pipe(Effect.provide(layerTest)),
1202 );
1203​
1204 it.effect("ignores a client favicon path hint", () =>
1205 Effect.gen(function* () {
1206 const fileSystem = yield* FileSystem.FileSystem;
1207 const path = yield* Path.Path;
1208 const root = yield* fileSystem.makeTempDirectoryScoped({
1209 prefix: "t3-asset-favicon-hint-",
1210 });
1211 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1212 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
1213 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1214​
1215 const result = yield* issueAssetUrl({
1216 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
1217 projectFaviconPath: "brand/saved.svg",
1218 });
1219​
1220 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
1221 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
1222 }).pipe(Effect.provide(layerTest)),
1223 );
1224​
1225 it.effect("serves a host's credentialed media through that host's driver", () => {
1226 const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
1227 const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
1228 const media = sourceControlDefinitions.mediaUrl(url)!;
1229 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
1231 driver: { kind: media.definition.kind, definition: media.definition },
1232 instance: fakeSourceControlDriverInstance(media.definition.kind, {
1233 pullRequests: null,
1234 fetchMedia: (request) =>
1235 Effect.sync(() => {
1236 fetched.push(request);
1237 return HttpClientResponse.fromWeb(
1238 HttpClientRequest.get(request.url),
1239 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
1240 );
1241 }),
1242 }),
1243 },
1244 ]);
1245 return Effect.gen(function* () {
1246 // Every client and server release spells the resource this way on the wire.
1247 const { resource } = yield* Schema.decodeEffect(AssetCreateUrlInput)({
1248 resource: { _tag: "github-media", cwd: "/repo", url },
1249 });
1250 const issued = yield* issueAssetUrl({ resource });
1251 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1252 const separator = suffix.indexOf("/");
1253 const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1254 expect(asset).toEqual({
1255 kind: "source-control-media",
1256 url: media.fetchUrl,
1257 cwd: "/repo",
1258 expiresAt: issued.expiresAt,
1259 });
1260 if (asset?.kind !== "source-control-media") return;
1261​
1262 const response = yield* sourceControlMediaResponse(asset, {
1263 range: "bytes=0-4",
1264 cookie: "session",
1265 });
1266 expect(fetched).toEqual([{ url: media.fetchUrl, headers: { range: "bytes=0-4" } }]);
1267 expect(response.status).toBe(206);
1268 // The upstream sent no type, so it comes from the file name the host gave the media.
1269 expect(response.headers["content-type"]).toBe("image/png");
1270 expect(response.headers["content-length"]).toBe("5");
1271 }).pipe(Effect.provide(Layer.merge(layerTest, layerDrivers)), Effect.scoped);
1272 });
1273​
1274 it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
1275 Effect.gen(function* () {
1276 for (const url of [
1277 "https://example.com/shot.png",
1278 "https://example.com/shot.png?token=private-media-token",
1279 ]) {
1280 const error = yield* issueAssetUrl({
1281 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
1282 }).pipe(Effect.flip);
1283 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1284 const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1285 expect(encoded).not.toContain(url);
1287 }).pipe(Effect.provide(layerTest)),
1288 );
1289});