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