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