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