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

AssetAccess.test.ts

1,495 lines63.5 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 AssetPreviewTypeValidationError,
8 ThreadId,
9 TurnItemId,
10} from "@t3tools/contracts";
11import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
12import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
13import { describe, expect, it } from "@effect/vitest";
14import * as Crypto from "effect/Crypto";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Redacted from "effect/Redacted";
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 { HttpClient, 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 { openMediaFile } from "./MediaFile.ts";
37import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
38import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
39import { githubMediaResponse } from "./GitHubMediaFetch.ts";
40import * as HostProcess from "@t3tools/shared/HostProcess";
41​
42vi.mock("node:fs/promises", async (importOriginal) => {
43 const actual = await importOriginal<typeof NodeFSP>();
44 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
45});
46​
47const layerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
48 prefix: "t3-asset-access-test-",
49});
50// A PNG header is enough for the dimension read: signature, then IHDR width and height.
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 it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
172 Effect.gen(function* () {
173 const fileSystem = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
176 const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
177 expect(error._tag).toBe("PlatformError");
178 expect(error.reason._tag).toBe("NotFound");
179 }).pipe(Effect.provide(NodeServices.layer)),
180 );
181 });
182​
183 it.effect("loads private media immediately after login with the GitHub credential", () => {
184 let lookups = 0;
185 const authorizations: Array<string | undefined> = [];
186 return Effect.gen(function* () {
187 const asset = {
188 url: "https://raw.githubusercontent.com/owner/repo/main/shot.png",
189 cwd: "/repo",
190 expiresAt: Number.MAX_SAFE_INTEGER,
191 };
192 expect((yield* githubMediaResponse(asset, {})).status).toBe(404);
193 expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
194 expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
195 // Caching the token is GitHubCredentials' job; this asks it every time.
196 expect(lookups).toBe(3);
197 expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
198 }).pipe(
199 Effect.provide(
200 Layer.mock(GitHubCredentials.GitHubCredentials)({
201 get: (host) =>
202 ++lookups === 1
203 ? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }))
204 : Effect.succeed({
205 host,
206 token: Redacted.make("signed-in"),
207 source: "gh" as const,
208 fingerprint: "fingerprint",
209 }),
210 }),
211 ),
212 Effect.provideService(
213 HttpClient.HttpClient,
214 HttpClient.make((request) => {
215 authorizations.push(request.headers.authorization);
216 return Effect.succeed(
217 HttpClientResponse.fromWeb(
218 request,
219 new Response(null, {
220 status: request.headers.authorization ? 200 : 404,
221 headers: { "content-type": "image/png" },
222 }),
223 ),
224 );
225 }),
226 ),
227 Effect.scoped,
228 );
229 });
230​
231 it.effect("serves an image a tool returned inline from the stored item", () =>
232 Effect.gen(function* () {
233 const resource = {
234 _tag: "tool-output-image" as const,
235 threadId: screenshotItem.threadId,
236 itemId: screenshotItem.id,
237 index: 0,
238 };
239 const result = yield* issueAssetUrl({ resource });
240 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
241 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
242 const separator = suffix.indexOf("/");
243 expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({
244 kind: "bytes",
245 mimeType: "image/png",
246 bytes: Buffer.from(screenshotPng),
247 });
248 const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(
249 Effect.flip,
250 );
251 expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");
252 // Larger than a provider turn accepts, so it is never decoded.
253 const oversized = yield* issueAssetUrl({
254 resource: { ...resource, itemId: oversizedScreenshotItem.id },
255 }).pipe(Effect.flip);
256 expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");
257 }).pipe(Effect.provide(layerTest)),
258 );
259​
260 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
261 Effect.gen(function* () {
262 const fs = yield* FileSystem.FileSystem;
263 const path = yield* Path.Path;
264 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
265 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
266 for (const [name, mimeType] of [
267 ["screenshot.png", "image/png"],
268 ["recording.mp4", "video/mp4"],
269 ["recording.webm", "video/webm"],
270 ["report.html", "text/html"],
271 ["report.pdf", "application/pdf"],
272 ] as const) {
273 const filePath = path.join(outside, name);
274 yield* fs.writeFileString(filePath, "media");
275 const canonicalFile = yield* fs.realPath(filePath);
276 const result = yield* issueAssetUrl({
277 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
278 workspaceRoot: root,
279 });
280 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
281 const separator = suffix.indexOf("/");
282 const token = suffix.slice(0, separator);
283 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
284 kind: "file",
285 path: canonicalFile,
286 mimeType,
287 });
288 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
289 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
290 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
291 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
292 }
293 }).pipe(Effect.provide(layerTest)),
294 );
295​
296 it.effect("reports pixel dimensions from an image header and nothing for other files", () =>
297 Effect.gen(function* () {
298 const fs = yield* FileSystem.FileSystem;
299 const path = yield* Path.Path;
300 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-dimensions-" });
301 const png = Uint8Array.from([
302 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0,
303 0x06, 0x40, 0, 0, 0x03, 0x84,
304 ]);
305 yield* fs.writeFile(path.join(root, "shot.png"), png);
306 yield* fs.writeFileString(path.join(root, "clip.mp4"), "video");
307 yield* fs.writeFileString(path.join(root, "broken.png"), "not a png");
308 const issue = (name: string) =>
309 issueAssetUrl({
310 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: name },
311 workspaceRoot: root,
312 });
313​
314 expect((yield* issue("shot.png")).imageDimensions).toEqual({ width: 1600, height: 900 });
315 expect((yield* issue("clip.mp4")).imageDimensions).toBeUndefined();
316 expect((yield* issue("broken.png")).imageDimensions).toBeUndefined();
317 }).pipe(Effect.provide(layerTest)),
318 );
319​
320 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
321 Effect.gen(function* () {
322 const fs = yield* FileSystem.FileSystem;
323 const path = yield* Path.Path;
324 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
325 const root = path.join(directory, "workspace");
326 yield* fs.makeDirectory(root);
327 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
328 const filePath = path.resolve(root, relativePath);
329 yield* fs.writeFileString(filePath, "media");
330 const result = yield* issueAssetUrl({
331 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
332 workspaceRoot: root,
333 });
334 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
335 const separator = suffix.indexOf("/");
336 expect(
337 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
338 ).toMatchObject({
339 kind: "file",
340 path: yield* fs.realPath(filePath),
341 });
342 }
343 }).pipe(Effect.provide(layerTest)),
344 );
345​
346 it.effect("resolves home-relative media paths independently of the workspace", () =>
347 Effect.gen(function* () {
348 const fs = yield* FileSystem.FileSystem;
349 const path = yield* Path.Path;
350 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
351 const home = path.join(directory, "var", "home", "alice");
352 const filePath = path.join(home, "Downloads", "repro.mp4");
353 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
354 yield* fs.writeFileString(filePath, "recording bytes");
355 const canonicalFile = yield* fs.realPath(filePath);
356 yield* Effect.gen(function* () {
357 for (const workspaceRoot of [
358 path.join(home, "project"),
359 path.join(directory, "srv", "project"),
360 undefined,
361 ]) {
362 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
363 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
364 const result = yield* issueAssetUrl({
365 resource: {
366 _tag: "media-file",
367 threadId: ThreadId.make("thread-1"),
368 path: requestedPath,
369 },
370 ...(workspaceRoot ? { workspaceRoot } : {}),
371 });
372 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
373 const separator = suffix.indexOf("/");
374 const asset = yield* resolveAsset(
375 suffix.slice(0, separator),
376 suffix.slice(separator + 1),
377 );
378 expect(asset).toMatchObject({
379 kind: "file",
380 path: canonicalFile,
381 mimeType: "video/mp4",
382 });
383 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
384 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
385 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
386 }
387 }
388 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
389 }).pipe(Effect.provide(layerTest)),
390 );
391​
392 it.effect.skipIf(!symlinksSupported)(
393 "rejects non-previewable files, disguised targets, and directories",
394 () =>
395 Effect.gen(function* () {
396 const fs = yield* FileSystem.FileSystem;
397 const path = yield* Path.Path;
398 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
399 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
400 const filePath = path.join(root, name);
401 yield* fs.writeFileString(filePath, "not media");
402 const error = yield* issueAssetUrl({
403 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
404 }).pipe(Effect.flip);
405 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
406 }
407 const disguisedPath = path.join(root, "disguised.png");
408 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
409 const disguisedError = yield* issueAssetUrl({
410 resource: {
411 _tag: "media-file",
412 threadId: ThreadId.make("thread-1"),
413 path: disguisedPath,
414 },
415 }).pipe(Effect.flip);
416 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
417 const directoryPath = path.join(root, "directory.png");
418 yield* fs.makeDirectory(directoryPath);
419 const directoryError = yield* issueAssetUrl({
420 resource: {
421 _tag: "media-file",
422 threadId: ThreadId.make("thread-1"),
423 path: directoryPath,
424 },
425 }).pipe(Effect.flip);
426 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
427 }).pipe(Effect.provide(layerTest)),
428 );
429​
430 it.effect.skipIf(!symlinksSupported)(
431 "binds media URLs to the canonical target and rejects symlink substitution",
432 () =>
433 Effect.gen(function* () {
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
437 const filePath = path.join(root, "actual.svg");
438 const aliasPath = path.join(root, "alias.png");
439 const replacementPath = path.join(root, "other.svg");
440 yield* fs.writeFileString(filePath, "<svg/>");
441 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
442 yield* fs.symlink(filePath, aliasPath);
443 const canonicalFile = yield* fs.realPath(filePath);
444 const result = yield* issueAssetUrl({
445 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
446 });
447 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
448 const separator = suffix.indexOf("/");
449 const token = suffix.slice(0, separator);
450 const name = suffix.slice(separator + 1);
451 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
452 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
453 yield* fs.remove(aliasPath);
454 yield* fs.symlink(replacementPath, aliasPath);
455 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
456 yield* fs.remove(filePath);
457 yield* fs.symlink(replacementPath, filePath);
458 expect(yield* resolveAsset(token, name)).toBeNull();
459 }).pipe(Effect.provide(layerTest)),
460 );
461​
462 it.effect.skipIf(!symlinksSupported)(
463 "keeps full and partial responses bound to the file opened during resolution",
464 () =>
465 Effect.gen(function* () {
466 const fs = yield* FileSystem.FileSystem;
467 const path = yield* Path.Path;
468 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
469 const filePath = path.join(root, "recording.mp4");
470 const savedPath = path.join(root, "saved.mp4");
471 const secretPath = path.join(root, "secret.txt");
472 yield* fs.writeFileString(filePath, "0123456789");
473 yield* fs.writeFileString(secretPath, "private information");
474 const result = yield* issueAssetUrl({
475 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
476 });
477 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
478 const separator = suffix.indexOf("/");
479 for (const [range, expected, status] of [
480 [undefined, "0123456789", 200],
481 ["bytes=2-5", "2345", 206],
482 ] as const) {
483 const asset = yield* resolveAsset(
484 suffix.slice(0, separator),
485 suffix.slice(separator + 1),
486 );
487 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
488​
489 yield* fs.rename(filePath, savedPath);
490 yield* fs.symlink(secretPath, filePath);
491 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
492 expect(response.status).toBe(status);
493 expect(response.headers.get("content-length")).toBe(String(expected.length));
494 expect(yield* Effect.promise(() => response.text())).toBe(expected);
495 yield* fs.remove(filePath);
496 yield* fs.rename(savedPath, filePath);
497 }
498 }).pipe(Effect.provide(layerTest)),
499 );
500​
501 it.effect.skipIf(!symlinksSupported)(
502 "rejects a symlink swapped in after canonical validation but before open",
503 () =>
504 Effect.gen(function* () {
505 const fs = yield* FileSystem.FileSystem;
506 const path = yield* Path.Path;
507 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
508 const filePath = path.join(root, "recording.mp4");
509 const secretPath = path.join(root, "secret.txt");
510 yield* fs.writeFileString(filePath, "video");
511 yield* fs.writeFileString(secretPath, "secret");
512 const canonicalPath = yield* fs.realPath(filePath);
513 const result = yield* issueAssetUrl({
514 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
515 });
516 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
517 const separator = suffix.indexOf("/");
518 const swappingFileSystem = FileSystem.FileSystem.of({
519 ...fs,
520 stat: Effect.fn(function* (requestedPath) {
521 const info = yield* fs.stat(requestedPath);
522 if (requestedPath === canonicalPath) {
523 yield* fs.remove(filePath);
524 yield* fs.symlink(secretPath, filePath);
525 }
526 return info;
527 }),
528 });
529 expect(
530 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
531 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
532 ),
533 ).toBeNull();
534 }).pipe(Effect.provide(layerTest)),
535 );
536​
537 it.effect.skipIf(!symlinksSupported)(
538 "closes a descriptor rejected when its path changes during open",
539 () =>
540 Effect.gen(function* () {
541 const fs = yield* FileSystem.FileSystem;
542 const path = yield* Path.Path;
543 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-rejected-" });
544 const filePath = path.join(root, "recording.mp4");
545 const secretPath = path.join(root, "secret.txt");
546 yield* fs.writeFileString(filePath, "video");
547 yield* fs.writeFileString(secretPath, "secret");
548 const canonicalPath = yield* fs.realPath(filePath);
549 const originalOpen = (yield* Effect.promise(() =>
550 vi.importActual<typeof NodeFSP>("node:fs/promises"),
551 )).open;
552 let opened: NodeFSP.FileHandle | undefined;
553 const openSpy = vi.mocked(NodeFSP.open).mockImplementation(async (target, flags, mode) => {
554 const handle = await originalOpen(target, flags, mode);
555 if (target === canonicalPath) {
556 opened = handle;
557 await NodeFSP.unlink(filePath);
558 await NodeFSP.symlink(secretPath, filePath);
559 }
560 return handle;
561 });
562 yield* Effect.addFinalizer(() =>
563 Effect.sync(() => openSpy.mockImplementation(originalOpen)),
564 );
565 expect(yield* openMediaFile(canonicalPath)).toBeNull();
566 expect(opened).toBeDefined();
567 expect(opened?.fd).toBe(-1);
568 }).pipe(Effect.provide(layerTest)),
569 );
570​
571 it.effect.skipIf(!symlinksSupported)(
572 "rejects an ancestor symlink race even when canonical path rechecks would pass",
573 () =>
574 Effect.gen(function* () {
575 const fs = yield* FileSystem.FileSystem;
576 const path = yield* Path.Path;
577 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
578 const publicDirectory = path.join(root, "public");
579 const privateDirectory = path.join(root, "private");
580 yield* fs.makeDirectory(publicDirectory);
581 yield* fs.makeDirectory(privateDirectory);
582 const filePath = path.join(publicDirectory, "recording.mp4");
583 yield* fs.writeFileString(filePath, "public video");
584 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
585 const canonicalPath = yield* fs.realPath(filePath);
586 const result = yield* issueAssetUrl({
587 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
588 });
589 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
590 const separator = suffix.indexOf("/");
591 const native = yield* Effect.promise(() =>
592 vi.importActual<typeof NodeFSP>("node:fs/promises"),
593 );
594 const savedDirectory = path.join(root, "saved");
595 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
596 // A pathname-only guard can see the original parents during realpath,
597 // but the private file during both lstat calls and open.
598 await native.unlink(publicDirectory);
599 await native.rename(savedDirectory, publicDirectory);
600 const canonical = await native.realpath(canonicalPath);
601 await native.rename(publicDirectory, savedDirectory);
602 await native.symlink(privateDirectory, publicDirectory, "junction");
603 return canonical;
604 });
605 yield* Effect.addFinalizer(() =>
606 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
607 );
608 const swappingFileSystem = FileSystem.FileSystem.of({
609 ...fs,
610 realPath: Effect.fn(function* (requestedPath) {
611 const canonical = yield* fs.realPath(requestedPath);
612 if (requestedPath === canonicalPath) {
613 yield* fs.rename(publicDirectory, savedDirectory);
614 yield* Effect.promise(() =>
615 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
616 );
617 }
618 return canonical;
619 }),
620 });
621 expect(
622 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
623 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
624 ),
625 ).toBeNull();
626 }).pipe(Effect.provide(layerTest)),
627 );
628​
629 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
630 Effect.gen(function* () {
631 const fs = yield* FileSystem.FileSystem;
632 const path = yield* Path.Path;
633 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
634 const filePath = path.join(root, "recording.mp4");
635 yield* fs.writeFileString(filePath, "original");
636 const input = {
637 resource: {
638 _tag: "media-file" as const,
639 threadId: ThreadId.make("thread-1"),
640 path: filePath,
641 },
642 };
643 const original = yield* issueAssetUrl(input);
644 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
645 const separator = suffix.indexOf("/");
646 const token = suffix.slice(0, separator);
647 const name = suffix.slice(separator + 1);
648 yield* fs.writeFileString(filePath, "in-place edit");
649 const edited = yield* resolveAsset(token, name);
650 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
651 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
652 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
653​
654 const replacement = path.join(root, "replacement.mp4");
655 yield* fs.writeFileString(replacement, "replacement");
656 yield* fs.rename(replacement, filePath);
657 expect(yield* resolveAsset(token, name)).toBeNull();
658​
659 const renewed = yield* issueAssetUrl(input);
660 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
661 const renewedSeparator = renewedSuffix.indexOf("/");
662 const renewedAsset = yield* resolveAsset(
663 renewedSuffix.slice(0, renewedSeparator),
664 renewedSuffix.slice(renewedSeparator + 1),
665 );
666 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
667 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
668 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
669 yield* fs.remove(filePath);
670 expect(
671 yield* resolveAsset(
672 renewedSuffix.slice(0, renewedSeparator),
673 renewedSuffix.slice(renewedSeparator + 1),
674 ),
675 ).toBeNull();
676 }).pipe(Effect.provide(layerTest)),
677 );
678​
679 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
680 Effect.gen(function* () {
681 const fileSystem = yield* FileSystem.FileSystem;
682 const path = yield* Path.Path;
683 const root = yield* fileSystem.makeTempDirectoryScoped({
684 prefix: "t3-asset-workspace-",
685 });
686 const htmlPath = path.join(root, "report.html");
687 const cssPath = path.join(root, "report.css");
688 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
689 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
690 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
691 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
692 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
693​
694 const result = yield* issueAssetUrl({
695 resource: {
696 _tag: "workspace-file",
697 threadId: ThreadId.make("thread-1"),
698 path: htmlPath,
699 },
700 workspaceRoot: root,
701 });
702 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
703 const separatorIndex = suffix.indexOf("/");
704 const token = suffix.slice(0, separatorIndex);
705​
706 expect(yield* resolveAsset(token, "report.html")).toEqual({
707 kind: "file",
708 path: canonicalHtmlPath,
709 });
710 expect(yield* resolveAsset(token, "report.css")).toEqual({
711 kind: "file",
712 path: canonicalCssPath,
713 });
714 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
715 expect(yield* resolveAsset(token, ".env")).toBeNull();
716 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
717 }).pipe(Effect.provide(layerTest)),
718 );
719​
720 it.effect("rejects workspace files outside the authorized root", () =>
721 Effect.gen(function* () {
722 const fileSystem = yield* FileSystem.FileSystem;
723 const path = yield* Path.Path;
724 const root = yield* fileSystem.makeTempDirectoryScoped({
725 prefix: "t3-asset-root-",
726 });
727 const outside = yield* fileSystem.makeTempDirectoryScoped({
728 prefix: "t3-asset-outside-",
729 });
730 const htmlPath = path.join(outside, "report.html");
731 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
732​
733 const error = yield* issueAssetUrl({
734 resource: {
735 _tag: "workspace-file",
736 threadId: ThreadId.make("thread-1"),
737 path: htmlPath,
738 },
739 workspaceRoot: root,
740 }).pipe(Effect.flip);
741 expect(error.message).toBe("Workspace file path must be relative to the project root.");
742 expect(error).toMatchObject({
743 _tag: "AssetWorkspacePathValidationError",
744 resource: {
745 _tag: "workspace-file",
746 threadId: "thread-1",
747 path: htmlPath,
748 },
749 });
750 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
751 }).pipe(Effect.provide(layerTest)),
752 );
753​
754 it.effect("issues draft workspace URLs without a thread", () =>
755 Effect.gen(function* () {
756 const fileSystem = yield* FileSystem.FileSystem;
757 const path = yield* Path.Path;
758 const root = yield* fileSystem.makeTempDirectoryScoped({
759 prefix: "t3-asset-draft-",
760 });
761 const htmlPath = path.join(root, "report.html");
762 const cssPath = path.join(root, "report.css");
763 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
764 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
765 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
766 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
767​
768 const result = yield* issueAssetUrl({
769 resource: { _tag: "draft-workspace-file", cwd: root, path: "report.html" },
770 workspaceRoot: root,
771 });
772 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
773 const separatorIndex = suffix.indexOf("/");
774 const token = suffix.slice(0, separatorIndex);
775​
776 expect(yield* resolveAsset(token, "report.html")).toEqual({
777 kind: "file",
778 path: canonicalHtmlPath,
779 });
780 expect(yield* resolveAsset(token, "report.css")).toEqual({
781 kind: "file",
782 path: canonicalCssPath,
783 });
784 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
785 }).pipe(Effect.provide(layerTest)),
786 );
787​
788 it.effect("serves absolute draft media files exactly, wherever they live", () =>
789 Effect.gen(function* () {
790 const fileSystem = yield* FileSystem.FileSystem;
791 const path = yield* Path.Path;
792 const root = yield* fileSystem.makeTempDirectoryScoped({
793 prefix: "t3-asset-draft-root-",
794 });
795 const outside = yield* fileSystem.makeTempDirectoryScoped({
796 prefix: "t3-asset-draft-outside-",
797 });
798 const clipPath = path.join(outside, "clip.mp4");
799 yield* fileSystem.writeFileString(clipPath, "video");
800 const canonicalClipPath = yield* fileSystem.realPath(clipPath);
801​
802 const result = yield* issueAssetUrl({
803 resource: { _tag: "draft-workspace-file", cwd: root, path: clipPath },
804 workspaceRoot: root,
805 });
806 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
807 const separatorIndex = suffix.indexOf("/");
808 const token = suffix.slice(0, separatorIndex);
809​
810 expect(yield* resolveAsset(token, "clip.mp4")).toMatchObject({
811 kind: "file",
812 path: canonicalClipPath,
813 mimeType: "video/mp4",
814 });
815 expect(yield* resolveAsset(token, "other.mp4")).toBeNull();
816 }).pipe(Effect.provide(layerTest)),
817 );
818​
819 it.effect("falls back to the resource cwd for relative draft paths", () =>
820 Effect.gen(function* () {
821 const fileSystem = yield* FileSystem.FileSystem;
822 const path = yield* Path.Path;
823 const root = yield* fileSystem.makeTempDirectoryScoped({
824 prefix: "t3-asset-draft-fallback-",
825 });
826 const htmlPath = path.join(root, "report.html");
827 yield* fileSystem.writeFileString(htmlPath, "<p>draft</p>");
828 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
829​
830 const result = yield* issueAssetUrl({
831 resource: { _tag: "draft-workspace-file", cwd: root, path: "report.html" },
832 });
833 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
834 const separatorIndex = suffix.indexOf("/");
835 const token = suffix.slice(0, separatorIndex);
836​
837 expect(yield* resolveAsset(token, "report.html")).toEqual({
838 kind: "file",
839 path: canonicalHtmlPath,
840 });
841 }).pipe(Effect.provide(layerTest)),
842 );
843​
844 it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
845 Effect.gen(function* () {
846 const fileSystem = yield* FileSystem.FileSystem;
847 const path = yield* Path.Path;
848 const root = yield* fileSystem.makeTempDirectoryScoped({
849 prefix: "t3-asset-permission-root-",
850 });
851 const htmlPath = path.join(root, "report.html");
852 yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
853 const cause = PlatformError.systemError({
854 _tag: "PermissionDenied",
855 module: "FileSystem",
856 method: "realPath",
857 pathOrDescriptor: htmlPath,
858 });
859 const failingFileSystem = FileSystem.FileSystem.of({
860 ...fileSystem,
861 realPath: () => Effect.fail(cause),
862 });
863​
864 const error = yield* issueAssetUrl({
865 resource: {
866 _tag: "workspace-file",
867 threadId: ThreadId.make("thread-1"),
868 path: htmlPath,
869 },
870 workspaceRoot: root,
871 }).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
872​
873 expect(error.message).toBe("Failed to inspect the workspace asset.");
874 expect(error).toMatchObject({
875 _tag: "AssetWorkspaceAssetInspectionError",
876 resource: {
877 _tag: "workspace-file",
878 threadId: "thread-1",
879 path: htmlPath,
880 },
881 });
882 expect(error.cause).toBe(cause);
883 }).pipe(Effect.provide(layerTest)),
884 );
885​
886 it.effect("issues exact workspace URLs for image previews", () =>
887 Effect.gen(function* () {
888 const fileSystem = yield* FileSystem.FileSystem;
889 const path = yield* Path.Path;
890 const root = yield* fileSystem.makeTempDirectoryScoped({
891 prefix: "t3-asset-image-workspace-",
892 });
893 const assetsDirectory = path.join(root, "assets");
894 const imagePath = path.join(assetsDirectory, "icon.png");
895 const siblingPath = path.join(assetsDirectory, "other.png");
896 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
897 yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
898 yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
899 const canonicalImagePath = yield* fileSystem.realPath(imagePath);
900​
901 const result = yield* issueAssetUrl({
902 resource: {
903 _tag: "workspace-file",
904 threadId: ThreadId.make("thread-1"),
905 path: imagePath,
906 },
907 workspaceRoot: root,
908 });
909 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
910 const separatorIndex = suffix.indexOf("/");
911 const token = suffix.slice(0, separatorIndex);
912​
913 expect(yield* resolveAsset(token, "icon.png")).toEqual({
914 kind: "file",
915 path: canonicalImagePath,
916 });
917 expect(yield* resolveAsset(token, "other.png")).toBeNull();
918 expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
919 }).pipe(Effect.provide(layerTest)),
920 );
921​
922 it.effect("previews workspace files with literal fragment characters in their paths", () =>
923 Effect.gen(function* () {
924 const fileSystem = yield* FileSystem.FileSystem;
925 const path = yield* Path.Path;
926 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
927 const directory = path.join(root, "assets#archive");
928 yield* fileSystem.makeDirectory(directory);
929​
930 for (const name of ["icon#v2.png", "report#draft.pdf"]) {
931 const filePath = path.join(directory, name);
932 yield* fileSystem.writeFileString(filePath, "preview fixture");
933 const canonicalFile = yield* fileSystem.realPath(filePath);
934 const result = yield* issueAssetUrl({
935 resource: {
936 _tag: "workspace-file",
937 threadId: ThreadId.make("thread-1"),
938 path: filePath,
939 },
940 workspaceRoot: root,
941 });
942 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
943 const token = suffix.slice(0, suffix.indexOf("/"));
944​
945 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
946 if (name.endsWith(".png")) {
947 expect(yield* resolveAsset(token, "other.png")).toBeNull();
948 }
949 }
950​
951 const disguisedPath = path.join(root, "image.png#notes.txt");
952 yield* fileSystem.writeFileString(disguisedPath, "not an image");
953 const error = yield* issueAssetUrl({
954 resource: {
955 _tag: "workspace-file",
956 threadId: ThreadId.make("thread-1"),
957 path: disguisedPath,
958 },
959 workspaceRoot: root,
960 }).pipe(Effect.flip);
961 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
962 }).pipe(Effect.provide(layerTest)),
963 );
964​
965 it.effect("signs MCP render intent only for inline HTML attachments", () =>
966 Effect.gen(function* () {
967 const config = yield* ServerConfig.ServerConfig;
968 const fs = yield* FileSystem.FileSystem;
969 const path = yield* Path.Path;
970 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
971 for (const extension of ["html", "pdf"]) {
972 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
973 yield* fs.writeFileString(
974 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
975 "capture",
976 );
977 for (const disposition of ["inline", "attachment"] as const) {
978 const result = yield* issueAssetUrl({
979 resource: {
980 _tag: "attachment",
981 attachmentId,
982 disposition,
983 renderIntent: "mcp-app",
984 },
985 });
986 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
987 const separator = suffix.indexOf("/");
988 const asset = yield* resolveAsset(
989 suffix.slice(0, separator),
990 suffix.slice(separator + 1),
991 );
992 if (asset?.kind !== "file") throw new Error("Expected attachment file");
993 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
994 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
995 );
996 // Changing signed claims cannot opt an ordinary download into rendering.
997 const token = suffix.slice(0, separator);
998 const [payload, signature] = token.split(".");
999 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1000 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1001 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1002 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1005 }).pipe(Effect.provide(layerTest)),
1006 );
1007​
1008 it.effect("issues exact attachment capabilities by attachment id", () =>
1009 Effect.gen(function* () {
1010 const config = yield* ServerConfig.ServerConfig;
1011 const fileSystem = yield* FileSystem.FileSystem;
1012 const path = yield* Path.Path;
1013 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
1014 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
1015 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1016 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1017​
1018 const result = yield* issueAssetUrl({
1019 resource: { _tag: "attachment", attachmentId },
1020 });
1021 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1022 const separatorIndex = suffix.indexOf("/");
1023 const token = suffix.slice(0, separatorIndex);
1024​
1025 expect(yield* resolveAsset(token, "ignored.png")).toEqual({
1026 kind: "file",
1027 path: attachmentPath,
1028 });
1029 }).pipe(Effect.provide(layerTest)),
1030 );
1031​
1032 it.effect("serves video attachments inline", () =>
1033 Effect.gen(function* () {
1034 const config = yield* ServerConfig.ServerConfig;
1035 const fileSystem = yield* FileSystem.FileSystem;
1036 const path = yield* Path.Path;
1037 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-mp4";
1038 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.mp4`);
1039 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1040 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1041​
1042 const result = yield* issueAssetUrl({
1043 resource: {
1044 _tag: "attachment",
1045 attachmentId,
1046 fileName: "demo.mp4",
1047 mimeType: 'video/mp4; codecs="avc1.42E01E"',
1048 },
1049 });
1050 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1051 const separatorIndex = suffix.indexOf("/");
1052​
1053 expect(
1054 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1055 ).toEqual({
1056 kind: "file",
1057 path: attachmentPath,
1058 fileName: "demo.mp4",
1059 mimeType: "video/mp4",
1060 });
1061 }).pipe(Effect.provide(layerTest)),
1062 );
1063 it.effect("issues signed native application icon capabilities", () =>
1064 Effect.gen(function* () {
1065 const result = yield* issueAssetUrl({
1066 resource: {
1067 _tag: "native-app-icon",
1068 app: { _tag: "app-id", appId: "com.example.Editor" },
1069 },
1070 });
1071​
1072 expect(result.relativeUrl).toMatch(
1073 new RegExp(`^${ASSET_ROUTE_PREFIX}/[^/]+/native-app-icon\\.png$`, "u"),
1074 );
1075 expect(result.expiresAt).toBeGreaterThan(0);
1076 }).pipe(Effect.provide(layerTest)),
1077 );
1078​
1079 it.effect("serves document attachments inline when a viewer requests it", () =>
1080 Effect.gen(function* () {
1081 const config = yield* ServerConfig.ServerConfig;
1082 const fileSystem = yield* FileSystem.FileSystem;
1083 const path = yield* Path.Path;
1084 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-pdf";
1085 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
1086 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1087 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1088​
1089 const result = yield* issueAssetUrl({
1090 resource: {
1091 _tag: "attachment",
1092 attachmentId,
1093 fileName: "report.pdf",
1094 mimeType: "application/pdf",
1095 disposition: "inline",
1096 },
1097 });
1098 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1099 const separatorIndex = suffix.indexOf("/");
1100​
1101 expect(
1102 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1103 ).toEqual({
1104 kind: "file",
1105 path: attachmentPath,
1106 fileName: "report.pdf",
1107 mimeType: "application/pdf",
1108 });
1109 }).pipe(Effect.provide(layerTest)),
1110 );
1111​
1112 it.effect("serves audio previews with their stored format and keeps saving explicit", () =>
1113 Effect.gen(function* () {
1114 const config = yield* ServerConfig.ServerConfig;
1115 const fileSystem = yield* FileSystem.FileSystem;
1116 const path = yield* Path.Path;
1117 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000003-wav";
1118 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.wav`);
1119 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1120 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1121 for (const disposition of ["inline", "attachment"] as const) {
1122 const result = yield* issueAssetUrl({
1123 resource: {
1124 _tag: "attachment",
1125 attachmentId,
1126 fileName: "recording.wav",
1127 mimeType: "application/octet-stream",
1128 disposition,
1129 },
1130 });
1131 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1132 const separatorIndex = suffix.indexOf("/");
1133 expect(
1134 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1135 ).toEqual({
1136 kind: "file",
1137 path: attachmentPath,
1138 fileName: "recording.wav",
1139 mimeType: disposition === "inline" ? "audio/wav" : "application/octet-stream",
1140 ...(disposition === "attachment" ? { download: true } : {}),
1141 });
1143 }).pipe(Effect.provide(layerTest)),
1144 );
1145​
1146 it.effect("keeps inline requests for other attachment types as downloads", () =>
1147 Effect.gen(function* () {
1148 const config = yield* ServerConfig.ServerConfig;
1149 const fileSystem = yield* FileSystem.FileSystem;
1150 const path = yield* Path.Path;
1151 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";
1152 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);
1153 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1154 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1155​
1156 const result = yield* issueAssetUrl({
1157 resource: {
1158 _tag: "attachment",
1159 attachmentId,
1160 fileName: "archive.zip",
1161 mimeType: "text/html",
1162 disposition: "inline",
1163 },
1164 });
1165 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1166 const separatorIndex = suffix.indexOf("/");
1167​
1168 expect(
1169 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1170 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
1171 }).pipe(Effect.provide(layerTest)),
1172 );
1173 it.effect("issues project favicon capabilities with a signed fallback", () =>
1174 Effect.gen(function* () {
1175 const fileSystem = yield* FileSystem.FileSystem;
1176 const path = yield* Path.Path;
1177 const root = yield* fileSystem.makeTempDirectoryScoped({
1178 prefix: "t3-asset-favicon-",
1179 });
1180 const faviconPath = path.join(root, "favicon.svg");
1181 const initialFavicon = "<svg>a</svg>";
1182 const updatedFavicon = "<svg>b</svg>";
1183 expect(updatedFavicon).toHaveLength(initialFavicon.length);
1184 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
1185 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
1186​
1187 const faviconResult = yield* issueAssetUrl({
1188 resource: { _tag: "project-favicon", cwd: root },
1189 });
1190 expect(faviconResult.sourcePath).toBe("favicon.svg");
1191 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1192 expect(
1193 yield* issueAssetUrl({
1194 resource: { _tag: "project-favicon", cwd: root },
1195 }),
1196 ).toEqual(faviconResult);
1197 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1198 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
1199 expect(
1200 yield* resolveAsset(
1201 faviconSuffix.slice(0, faviconSeparatorIndex),
1202 faviconSuffix.slice(faviconSeparatorIndex + 1),
1203 ),
1204 ).toEqual({ kind: "file", path: canonicalFaviconPath });
1205​
1206 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
1207 const updatedFaviconResult = yield* issueAssetUrl({
1208 resource: { _tag: "project-favicon", cwd: root },
1209 });
1210 expect(
1211 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
1212 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
1213​
1214 yield* fileSystem.remove(faviconPath);
1215 const fallbackResult = yield* issueAssetUrl({
1216 resource: { _tag: "project-favicon", cwd: root },
1217 });
1218 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
1219 expect(fallbackResult.sourcePath).toBeUndefined();
1220 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1221 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
1222 expect(
1223 yield* resolveAsset(
1224 fallbackSuffix.slice(0, fallbackSeparatorIndex),
1225 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
1226 ),
1227 ).toBeNull();
1228 }).pipe(Effect.provide(layerTest)),
1229 );
1230​
1231 it.effect("issues project favicon capabilities for a saved override", () =>
1232 Effect.gen(function* () {
1233 const fileSystem = yield* FileSystem.FileSystem;
1234 const path = yield* Path.Path;
1235 const root = yield* fileSystem.makeTempDirectoryScoped({
1236 prefix: "t3-asset-favicon-override-",
1237 });
1238 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1239 yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
1240 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
1241​
1242 const result = yield* issueAssetUrl({
1243 resource: { _tag: "project-favicon", cwd: root },
1244 projectFaviconPath: "brand/custom.svg",
1245 });
1246​
1247 expect(result.sourcePath).toBe(path.join("brand", "custom.svg"));
1248 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
1249 }).pipe(Effect.provide(layerTest)),
1250 );
1251​
1252 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
1253 Effect.gen(function* () {
1254 const fileSystem = yield* FileSystem.FileSystem;
1255 const path = yield* Path.Path;
1256 const root = yield* fileSystem.makeTempDirectoryScoped({
1257 prefix: "t3-asset-favicon-workspace-",
1258 });
1259 const pictures = yield* fileSystem.makeTempDirectoryScoped({
1260 prefix: "t3-asset-favicon-pictures-",
1261 });
1262 const externalPath = path.join(pictures, "custom.png");
1263 const siblingPath = path.join(pictures, "sibling.png");
1264 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
1265 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
1266 const canonicalPath = yield* fileSystem.realPath(externalPath);
1267 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
1268​
1269 const result = yield* issueAssetUrl({
1270 resource: { _tag: "project-favicon", cwd: root },
1271 projectFaviconPath: externalPath,
1272 });
1273 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1274 const separatorIndex = suffix.indexOf("/");
1275​
1276 expect(result.sourcePath).toBe(externalPath);
1277 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
1278 expect(
1279 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1280 ).toEqual({ kind: "file", path: canonicalPath });
1281 const tamperedSuffixResult = yield* resolveAsset(
1282 suffix.slice(0, separatorIndex),
1283 "sibling.png",
1284 );
1285 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
1286 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
1287 }).pipe(Effect.provide(layerTest)),
1288 );
1289​
1290 it.effect("ignores a client favicon path hint", () =>
1291 Effect.gen(function* () {
1292 const fileSystem = yield* FileSystem.FileSystem;
1293 const path = yield* Path.Path;
1294 const root = yield* fileSystem.makeTempDirectoryScoped({
1295 prefix: "t3-asset-favicon-hint-",
1296 });
1297 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1298 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
1299 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1300​
1301 const result = yield* issueAssetUrl({
1302 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
1303 projectFaviconPath: "brand/saved.svg",
1304 });
1305​
1306 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
1307 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
1308 }).pipe(Effect.provide(layerTest)),
1309 );
1310​
1311 it.effect("keeps automatic favicon resolution separate from a saved override", () =>
1312 Effect.gen(function* () {
1313 const fileSystem = yield* FileSystem.FileSystem;
1314 const path = yield* Path.Path;
1315 const root = yield* fileSystem.makeTempDirectoryScoped({
1316 prefix: "t3-asset-favicon-automatic-",
1317 });
1318 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1319 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1320 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
1321​
1322 const result = yield* issueAssetUrl({
1323 resource: { _tag: "project-favicon", cwd: root },
1324 });
1325​
1326 expect(result.sourcePath).toBe("favicon.svg");
1327 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1328 }).pipe(Effect.provide(layerTest)),
1329 );
1330​
1331 it.effect("serves a native macOS app icon as its embedded PNG", () =>
1332 Effect.gen(function* () {
1333 const fileSystem = yield* FileSystem.FileSystem;
1334 const path = yield* Path.Path;
1335 const root = yield* fileSystem.makeTempDirectoryScoped({
1336 prefix: "t3-asset-favicon-icns-",
1337 });
1338 const icns = new Uint8Array(8 + 8 + screenshotPng.length);
1339 icns.set(new TextEncoder().encode("icns"));
1340 new DataView(icns.buffer).setUint32(4, icns.length);
1341 icns.set(new TextEncoder().encode("ic07"), 8);
1342 new DataView(icns.buffer).setUint32(12, 8 + screenshotPng.length);
1343 icns.set(screenshotPng, 16);
1344 yield* fileSystem.makeDirectory(path.join(root, "Resources"));
1345 yield* fileSystem.writeFile(path.join(root, "Resources", "AppIcon.icns"), icns);
1346​
1347 const result = yield* issueAssetUrl({
1348 resource: { _tag: "project-favicon", cwd: root },
1349 });
1350 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1351 const separatorIndex = suffix.indexOf("/");
1352​
1353 expect(result.sourcePath).toBe(path.join("Resources", "AppIcon.icns"));
1354 const asset = yield* resolveAsset(
1355 suffix.slice(0, separatorIndex),
1356 suffix.slice(separatorIndex + 1),
1357 );
1358 expect(asset?.kind === "bytes" ? asset.mimeType : null).toBe("image/png");
1359 expect(asset?.kind === "bytes" ? Uint8Array.from(asset.bytes) : null).toEqual(screenshotPng);
1360 }).pipe(Effect.provide(layerTest)),
1361 );
1362​
1363 it.effect("rejects a resolved project favicon with a non-image extension", () =>
1364 Effect.gen(function* () {
1365 const fileSystem = yield* FileSystem.FileSystem;
1366 const path = yield* Path.Path;
1367 const root = yield* fileSystem.makeTempDirectoryScoped({
1368 prefix: "t3-asset-favicon-type-",
1369 });
1370 yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
1371​
1372 const error = yield* issueAssetUrl({
1373 resource: { _tag: "project-favicon", cwd: root },
1374 projectFaviconPath: "secret.txt",
1375 }).pipe(Effect.flip);
1376​
1377 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
1378 }).pipe(Effect.provide(layerTest)),
1379 );
1380​
1381 it.effect("buckets project favicon expiry after content hashing", () =>
1382 Effect.gen(function* () {
1383 const crypto = yield* Crypto.Crypto;
1384 const fileSystem = yield* FileSystem.FileSystem;
1385 const path = yield* Path.Path;
1386 const root = yield* fileSystem.makeTempDirectoryScoped({
1387 prefix: "t3-asset-favicon-expiry-",
1388 });
1389 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
1390​
1391 const bucketMs = 30 * 60 * 1000;
1392 yield* TestClock.setTime(bucketMs - 1);
1393 const crossingCrypto = Crypto.make({
1394 randomBytes: (size) => new Uint8Array(size),
1395 digest: (algorithm, data) =>
1396 TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
1397 });
1398 const result = yield* issueAssetUrl({
1399 resource: { _tag: "project-favicon", cwd: root },
1400 }).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
1401​
1402 expect(result.expiresAt).toBe(3 * bucketMs);
1403 }).pipe(Effect.provide(layerTest)),
1404 );
1405​
1406 it.effect("preserves structured project favicon resolution causes", () =>
1407 Effect.gen(function* () {
1408 const fileSystem = yield* FileSystem.FileSystem;
1409 const root = yield* fileSystem.makeTempDirectoryScoped({
1410 prefix: "t3-asset-favicon-error-",
1411 });
1412 const platformCause = PlatformError.systemError({
1413 _tag: "PermissionDenied",
1414 module: "FileSystem",
1415 method: "stat",
1416 });
1417 const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
1418 operation: "stat-candidate",
1419 workspaceRoot: root,
1420 relativePath: "favicon.svg",
1421 cause: platformCause,
1422 });
1423 const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
1424 resolvePath: () => Effect.fail(resolutionCause),
1425 });
1426​
1427 const error = yield* issueAssetUrl({
1428 resource: { _tag: "project-favicon", cwd: root },
1429 }).pipe(
1430 Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
1431 Effect.flip,
1432 );
1433​
1434 expect(error.message).toBe("Failed to resolve project favicon.");
1435 expect(error._tag).toBe("AssetProjectFaviconResolutionError");
1436 expect(error.cause).toBe(resolutionCause);
1437 }).pipe(Effect.provide(layerTest)),
1438 );
1439​
1440 it.effect("serves GitHub-hosted pull request media through the repository's credential", () =>
1441 Effect.gen(function* () {
1442 const resolve = (relativeUrl: string) => {
1443 const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1444 const separator = suffix.indexOf("/");
1445 return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1446 };
1447 const issue = (url: string) =>
1448 issueAssetUrl({ resource: { _tag: "github-media", cwd: "/repo", url } });
1449​
1450 const attachment = yield* issue(
1451 "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
1452 );
1453 expect(attachment.relativeUrl.endsWith("/1a1842fb-6383-492f-873c-57aa0033fa6c")).toBe(true);
1454 expect(yield* resolve(attachment.relativeUrl)).toEqual({
1455 kind: "github-media",
1456 url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
1457 cwd: "/repo",
1458 // The signed URL's own expiry, which is how long a client may keep the bytes.
1459 expiresAt: attachment.expiresAt,
1460 });
1461​
1462 // A `blob` link addresses the page; only the raw host answers a credential with bytes.
1463 const committed = yield* issue("https://github.com/owner/repo/blob/main/docs/shot.png");
1464 expect(yield* resolve(committed.relativeUrl)).toMatchObject({
1465 url: "https://raw.githubusercontent.com/owner/repo/main/docs/shot.png",
1466 });
1467​
1468 // The pre-`user-attachments` form, Git LFS bytes, and a name no `decodeURIComponent`
1469 // accepts all arrive from real bodies.
1470 const legacy = yield* issue("https://github.com/owner/repo/assets/45952064/1a1842fb");
1471 expect(yield* resolve(legacy.relativeUrl)).toMatchObject({
1472 url: "https://github.com/owner/repo/assets/45952064/1a1842fb",
1473 });
1474 const lfs = yield* issue("https://media.githubusercontent.com/media/owner/repo/main/a.mp4");
1475 expect(yield* resolve(lfs.relativeUrl)).toMatchObject({
1476 url: "https://media.githubusercontent.com/media/owner/repo/main/a.mp4",
1477 });
1478 const awkward = yield* issue("https://raw.githubusercontent.com/o/r/main/100%.png");
1479 expect(awkward.relativeUrl.endsWith("/100%25.png")).toBe(true);
1480​
1481 for (const url of [
1482 "https://example.com/shot.png",
1483 "https://example.com/shot.png?token=private-media-token",
1484 "http://github.com/user-attachments/assets/1a1842fb",
1485 "https://github.com/owner/repo/pull/1",
1486 "https://github.com/owner/repo/blob/main/",
1487 ]) {
1488 const error = yield* issue(url).pipe(Effect.flip);
1489 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1490 const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1491 expect(encoded).not.toContain(url);
1493 }).pipe(Effect.provide(layerTest)),
1494 );
1495});