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 { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
6import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
7import { describe, expect, it } from "@effect/vitest";
8import * as Crypto from "effect/Crypto";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpServerResponse } from "effect/unstable/http";
16import { vi } from "vite-plus/test";
17
18import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
19import * as ServerConfig from "../config.ts";
20import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
21import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
22import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
23import { assetFileResponse } from "../http.ts";
24import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
25import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
26import { openMediaFile } from "./MediaFile.ts";
27import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
28
29vi.mock("node:fs/promises", async (importOriginal) => {
30 const actual = await importOriginal<typeof NodeFSP>();
31 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
32});
33
34const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
35 prefix: "t3-asset-access-test-",
36});
37const testLayer = Layer.mergeAll(
38 NodeHttpPlatform.layer,
39 configLayer,
40 WorkspacePaths.layer,
41 ProjectFaviconResolver.layer.pipe(
42 Layer.provide(WorkspacePaths.layer),
43 Layer.provide(T3ProjectFileLoader.layer),
44 ),
45 NativeAppIconResolver.layer.pipe(Layer.provide(configLayer)),
46 ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
47).pipe(Layer.provideMerge(NodeServices.layer));
48
49describe("AssetAccess", () => {
50 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
51 Effect.gen(function* () {
52 const fs = yield* FileSystem.FileSystem;
53 const path = yield* Path.Path;
54 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
55 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
56 for (const [name, mimeType] of [
57 ["screenshot.png", "image/png"],
58 ["recording.mp4", "video/mp4"],
59 ["recording.webm", "video/webm"],
60 ["report.html", "text/html"],
61 ["report.pdf", "application/pdf"],
62 ] as const) {
63 const filePath = path.join(outside, name);
64 yield* fs.writeFileString(filePath, "media");
65 const canonicalFile = yield* fs.realPath(filePath);
66 const result = yield* issueAssetUrl({
67 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
68 workspaceRoot: root,
69 });
70 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
71 const separator = suffix.indexOf("/");
72 const token = suffix.slice(0, separator);
73 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
74 kind: "file",
75 path: canonicalFile,
76 mimeType,
77 });
78 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
79 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
80 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
81 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
82 }
83 }).pipe(Effect.provide(testLayer)),
84 );
85
86 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
87 Effect.gen(function* () {
88 const fs = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
91 const root = path.join(directory, "workspace");
92 yield* fs.makeDirectory(root);
93 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
94 const filePath = path.resolve(root, relativePath);
95 yield* fs.writeFileString(filePath, "media");
96 const result = yield* issueAssetUrl({
97 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
98 workspaceRoot: root,
99 });
100 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
101 const separator = suffix.indexOf("/");
102 expect(
103 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
104 ).toMatchObject({
105 kind: "file",
106 path: yield* fs.realPath(filePath),
107 });
108 }
109 }).pipe(Effect.provide(testLayer)),
110 );
111
112 it.effect.skipIf(!symlinksSupported)(
113 "rejects non-previewable files, disguised targets, and directories",
114 () =>
115 Effect.gen(function* () {
116 const fs = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
119 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
120 const filePath = path.join(root, name);
121 yield* fs.writeFileString(filePath, "not media");
122 const error = yield* issueAssetUrl({
123 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
124 }).pipe(Effect.flip);
125 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
126 }
127 const disguisedPath = path.join(root, "disguised.png");
128 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
129 const disguisedError = yield* issueAssetUrl({
130 resource: {
131 _tag: "media-file",
132 threadId: ThreadId.make("thread-1"),
133 path: disguisedPath,
134 },
135 }).pipe(Effect.flip);
136 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
137 const directoryPath = path.join(root, "directory.png");
138 yield* fs.makeDirectory(directoryPath);
139 const directoryError = yield* issueAssetUrl({
140 resource: {
141 _tag: "media-file",
142 threadId: ThreadId.make("thread-1"),
143 path: directoryPath,
144 },
145 }).pipe(Effect.flip);
146 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
147 }).pipe(Effect.provide(testLayer)),
148 );
149
150 it.effect.skipIf(!symlinksSupported)(
151 "binds media URLs to the canonical target and rejects symlink substitution",
152 () =>
153 Effect.gen(function* () {
154 const fs = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
157 const filePath = path.join(root, "actual.svg");
158 const aliasPath = path.join(root, "alias.png");
159 const replacementPath = path.join(root, "other.svg");
160 yield* fs.writeFileString(filePath, "<svg/>");
161 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
162 yield* fs.symlink(filePath, aliasPath);
163 const canonicalFile = yield* fs.realPath(filePath);
164 const result = yield* issueAssetUrl({
165 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
166 });
167 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
168 const separator = suffix.indexOf("/");
169 const token = suffix.slice(0, separator);
170 const name = suffix.slice(separator + 1);
171 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
172 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
173 yield* fs.remove(aliasPath);
174 yield* fs.symlink(replacementPath, aliasPath);
175 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
176 yield* fs.remove(filePath);
177 yield* fs.symlink(replacementPath, filePath);
178 expect(yield* resolveAsset(token, name)).toBeNull();
179 }).pipe(Effect.provide(testLayer)),
180 );
181
182 it.effect.skipIf(!symlinksSupported)(
183 "keeps full and partial responses bound to the file opened during resolution",
184 () =>
185 Effect.gen(function* () {
186 const fs = yield* FileSystem.FileSystem;
187 const path = yield* Path.Path;
188 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
189 const filePath = path.join(root, "recording.mp4");
190 const savedPath = path.join(root, "saved.mp4");
191 const secretPath = path.join(root, "secret.txt");
192 yield* fs.writeFileString(filePath, "0123456789");
193 yield* fs.writeFileString(secretPath, "private information");
194 const result = yield* issueAssetUrl({
195 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
196 });
197 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
198 const separator = suffix.indexOf("/");
199 for (const [range, expected, status] of [
200 [undefined, "0123456789", 200],
201 ["bytes=2-5", "2345", 206],
202 ] as const) {
203 const asset = yield* resolveAsset(
204 suffix.slice(0, separator),
205 suffix.slice(separator + 1),
206 );
207 if (!asset) throw new Error("Expected a resolved media file");
208
209 yield* fs.rename(filePath, savedPath);
210 yield* fs.symlink(secretPath, filePath);
211 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
212 expect(response.status).toBe(status);
213 expect(response.headers.get("content-length")).toBe(String(expected.length));
214 expect(yield* Effect.promise(() => response.text())).toBe(expected);
215 yield* fs.remove(filePath);
216 yield* fs.rename(savedPath, filePath);
217 }
218 }).pipe(Effect.provide(testLayer)),
219 );
220
221 it.effect.skipIf(!symlinksSupported)(
222 "rejects a symlink swapped in after canonical validation but before open",
223 () =>
224 Effect.gen(function* () {
225 const fs = yield* FileSystem.FileSystem;
226 const path = yield* Path.Path;
227 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
228 const filePath = path.join(root, "recording.mp4");
229 const secretPath = path.join(root, "secret.txt");
230 yield* fs.writeFileString(filePath, "video");
231 yield* fs.writeFileString(secretPath, "secret");
232 const canonicalPath = yield* fs.realPath(filePath);
233 const result = yield* issueAssetUrl({
234 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
235 });
236 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
237 const separator = suffix.indexOf("/");
238 const swappingFileSystem = FileSystem.FileSystem.of({
239 ...fs,
240 stat: Effect.fn(function* (requestedPath) {
241 const info = yield* fs.stat(requestedPath);
242 if (requestedPath === canonicalPath) {
243 yield* fs.remove(filePath);
244 yield* fs.symlink(secretPath, filePath);
245 }
246 return info;
247 }),
248 });
249 expect(
250 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
251 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
252 ),
253 ).toBeNull();
254 }).pipe(Effect.provide(testLayer)),
255 );
256
257 it.effect.skipIf(!symlinksSupported)(
258 "closes a descriptor rejected when its path changes during open",
259 () =>
260 Effect.gen(function* () {
261 const fs = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-rejected-" });
264 const filePath = path.join(root, "recording.mp4");
265 const secretPath = path.join(root, "secret.txt");
266 yield* fs.writeFileString(filePath, "video");
267 yield* fs.writeFileString(secretPath, "secret");
268 const canonicalPath = yield* fs.realPath(filePath);
269 const originalOpen = (yield* Effect.promise(() =>
270 vi.importActual<typeof NodeFSP>("node:fs/promises"),
271 )).open;
272 let opened: NodeFSP.FileHandle | undefined;
273 const openSpy = vi.mocked(NodeFSP.open).mockImplementation(async (target, flags, mode) => {
274 const handle = await originalOpen(target, flags, mode);
275 if (target === canonicalPath) {
276 opened = handle;
277 await NodeFSP.unlink(filePath);
278 await NodeFSP.symlink(secretPath, filePath);
279 }
280 return handle;
281 });
282 yield* Effect.addFinalizer(() =>
283 Effect.sync(() => openSpy.mockImplementation(originalOpen)),
284 );
285 expect(yield* openMediaFile(canonicalPath)).toBeNull();
286 expect(opened).toBeDefined();
287 expect(opened?.fd).toBe(-1);
288 }).pipe(Effect.provide(testLayer)),
289 );
290
291 it.effect.skipIf(!symlinksSupported)(
292 "rejects an ancestor symlink race even when canonical path rechecks would pass",
293 () =>
294 Effect.gen(function* () {
295 const fs = yield* FileSystem.FileSystem;
296 const path = yield* Path.Path;
297 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
298 const publicDirectory = path.join(root, "public");
299 const privateDirectory = path.join(root, "private");
300 yield* fs.makeDirectory(publicDirectory);
301 yield* fs.makeDirectory(privateDirectory);
302 const filePath = path.join(publicDirectory, "recording.mp4");
303 yield* fs.writeFileString(filePath, "public video");
304 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
305 const canonicalPath = yield* fs.realPath(filePath);
306 const result = yield* issueAssetUrl({
307 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
308 });
309 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
310 const separator = suffix.indexOf("/");
311 const native = yield* Effect.promise(() =>
312 vi.importActual<typeof NodeFSP>("node:fs/promises"),
313 );
314 const savedDirectory = path.join(root, "saved");
315 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
316 // A pathname-only guard can see the original parents during realpath,
317 // but the private file during both lstat calls and open.
318 await native.unlink(publicDirectory);
319 await native.rename(savedDirectory, publicDirectory);
320 const canonical = await native.realpath(canonicalPath);
321 await native.rename(publicDirectory, savedDirectory);
322 await native.symlink(privateDirectory, publicDirectory, "junction");
323 return canonical;
324 });
325 yield* Effect.addFinalizer(() =>
326 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
327 );
328 const swappingFileSystem = FileSystem.FileSystem.of({
329 ...fs,
330 realPath: Effect.fn(function* (requestedPath) {
331 const canonical = yield* fs.realPath(requestedPath);
332 if (requestedPath === canonicalPath) {
333 yield* fs.rename(publicDirectory, savedDirectory);
334 yield* Effect.promise(() =>
335 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
336 );
337 }
338 return canonical;
339 }),
340 });
341 expect(
342 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
343 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
344 ),
345 ).toBeNull();
346 }).pipe(Effect.provide(testLayer)),
347 );
348
349 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
350 Effect.gen(function* () {
351 const fs = yield* FileSystem.FileSystem;
352 const path = yield* Path.Path;
353 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
354 const filePath = path.join(root, "recording.mp4");
355 yield* fs.writeFileString(filePath, "original");
356 const input = {
357 resource: {
358 _tag: "media-file" as const,
359 threadId: ThreadId.make("thread-1"),
360 path: filePath,
361 },
362 };
363 const original = yield* issueAssetUrl(input);
364 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
365 const separator = suffix.indexOf("/");
366 const token = suffix.slice(0, separator);
367 const name = suffix.slice(separator + 1);
368 yield* fs.writeFileString(filePath, "in-place edit");
369 const edited = yield* resolveAsset(token, name);
370 if (!edited) throw new Error("Expected the edited media file");
371 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
372 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
373
374 const replacement = path.join(root, "replacement.mp4");
375 yield* fs.writeFileString(replacement, "replacement");
376 yield* fs.rename(replacement, filePath);
377 expect(yield* resolveAsset(token, name)).toBeNull();
378
379 const renewed = yield* issueAssetUrl(input);
380 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
381 const renewedSeparator = renewedSuffix.indexOf("/");
382 const renewedAsset = yield* resolveAsset(
383 renewedSuffix.slice(0, renewedSeparator),
384 renewedSuffix.slice(renewedSeparator + 1),
385 );
386 if (!renewedAsset) throw new Error("Expected the replacement media file");
387 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
388 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
389 yield* fs.remove(filePath);
390 expect(
391 yield* resolveAsset(
392 renewedSuffix.slice(0, renewedSeparator),
393 renewedSuffix.slice(renewedSeparator + 1),
394 ),
395 ).toBeNull();
396 }).pipe(Effect.provide(testLayer)),
397 );
398
399 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
400 Effect.gen(function* () {
401 const fileSystem = yield* FileSystem.FileSystem;
402 const path = yield* Path.Path;
403 const root = yield* fileSystem.makeTempDirectoryScoped({
404 prefix: "t3-asset-workspace-",
405 });
406 const htmlPath = path.join(root, "report.html");
407 const cssPath = path.join(root, "report.css");
408 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
409 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
410 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
411 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
412 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
413
414 const result = yield* issueAssetUrl({
415 resource: {
416 _tag: "workspace-file",
417 threadId: ThreadId.make("thread-1"),
418 path: htmlPath,
419 },
420 workspaceRoot: root,
421 });
422 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
423 const separatorIndex = suffix.indexOf("/");
424 const token = suffix.slice(0, separatorIndex);
425
426 expect(yield* resolveAsset(token, "report.html")).toEqual({
427 kind: "file",
428 path: canonicalHtmlPath,
429 });
430 expect(yield* resolveAsset(token, "report.css")).toEqual({
431 kind: "file",
432 path: canonicalCssPath,
433 });
434 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
435 expect(yield* resolveAsset(token, ".env")).toBeNull();
436 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
437 }).pipe(Effect.provide(testLayer)),
438 );
439
440 it.effect("rejects workspace files outside the authorized root", () =>
441 Effect.gen(function* () {
442 const fileSystem = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const root = yield* fileSystem.makeTempDirectoryScoped({
445 prefix: "t3-asset-root-",
446 });
447 const outside = yield* fileSystem.makeTempDirectoryScoped({
448 prefix: "t3-asset-outside-",
449 });
450 const htmlPath = path.join(outside, "report.html");
451 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
452
453 const error = yield* issueAssetUrl({
454 resource: {
455 _tag: "workspace-file",
456 threadId: ThreadId.make("thread-1"),
457 path: htmlPath,
458 },
459 workspaceRoot: root,
460 }).pipe(Effect.flip);
461 expect(error.message).toBe("Workspace file path must be relative to the project root.");
462 expect(error).toMatchObject({
463 _tag: "AssetWorkspacePathValidationError",
464 resource: {
465 _tag: "workspace-file",
466 threadId: "thread-1",
467 path: htmlPath,
468 },
469 });
470 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
471 }).pipe(Effect.provide(testLayer)),
472 );
473
474 it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
475 Effect.gen(function* () {
476 const fileSystem = yield* FileSystem.FileSystem;
477 const path = yield* Path.Path;
478 const root = yield* fileSystem.makeTempDirectoryScoped({
479 prefix: "t3-asset-permission-root-",
480 });
481 const htmlPath = path.join(root, "report.html");
482 yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
483 const cause = PlatformError.systemError({
484 _tag: "PermissionDenied",
485 module: "FileSystem",
486 method: "realPath",
487 pathOrDescriptor: htmlPath,
488 });
489 const failingFileSystem = FileSystem.FileSystem.of({
490 ...fileSystem,
491 realPath: () => Effect.fail(cause),
492 });
493
494 const error = yield* issueAssetUrl({
495 resource: {
496 _tag: "workspace-file",
497 threadId: ThreadId.make("thread-1"),
498 path: htmlPath,
499 },
500 workspaceRoot: root,
501 }).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
502
503 expect(error.message).toBe("Failed to inspect the workspace asset.");
504 expect(error).toMatchObject({
505 _tag: "AssetWorkspaceAssetInspectionError",
506 resource: {
507 _tag: "workspace-file",
508 threadId: "thread-1",
509 path: htmlPath,
510 },
511 });
512 expect(error.cause).toBe(cause);
513 }).pipe(Effect.provide(testLayer)),
514 );
515
516 it.effect("issues exact workspace URLs for image previews", () =>
517 Effect.gen(function* () {
518 const fileSystem = yield* FileSystem.FileSystem;
519 const path = yield* Path.Path;
520 const root = yield* fileSystem.makeTempDirectoryScoped({
521 prefix: "t3-asset-image-workspace-",
522 });
523 const assetsDirectory = path.join(root, "assets");
524 const imagePath = path.join(assetsDirectory, "icon.png");
525 const siblingPath = path.join(assetsDirectory, "other.png");
526 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
527 yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
528 yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
529 const canonicalImagePath = yield* fileSystem.realPath(imagePath);
530
531 const result = yield* issueAssetUrl({
532 resource: {
533 _tag: "workspace-file",
534 threadId: ThreadId.make("thread-1"),
535 path: imagePath,
536 },
537 workspaceRoot: root,
538 });
539 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
540 const separatorIndex = suffix.indexOf("/");
541 const token = suffix.slice(0, separatorIndex);
542
543 expect(yield* resolveAsset(token, "icon.png")).toEqual({
544 kind: "file",
545 path: canonicalImagePath,
546 });
547 expect(yield* resolveAsset(token, "other.png")).toBeNull();
548 expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
549 }).pipe(Effect.provide(testLayer)),
550 );
551
552 it.effect("issues exact attachment capabilities by attachment id", () =>
553 Effect.gen(function* () {
554 const config = yield* ServerConfig.ServerConfig;
555 const fileSystem = yield* FileSystem.FileSystem;
556 const path = yield* Path.Path;
557 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
558 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
559 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
560 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
561
562 const result = yield* issueAssetUrl({
563 resource: { _tag: "attachment", attachmentId },
564 });
565 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
566 const separatorIndex = suffix.indexOf("/");
567 const token = suffix.slice(0, separatorIndex);
568
569 expect(yield* resolveAsset(token, "ignored.png")).toEqual({
570 kind: "file",
571 path: attachmentPath,
572 });
573 }).pipe(Effect.provide(testLayer)),
574 );
575
576 it.effect("serves video attachments inline", () =>
577 Effect.gen(function* () {
578 const config = yield* ServerConfig.ServerConfig;
579 const fileSystem = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-mp4";
582 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.mp4`);
583 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
584 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
585
586 const result = yield* issueAssetUrl({
587 resource: {
588 _tag: "attachment",
589 attachmentId,
590 fileName: "demo.mp4",
591 mimeType: 'video/mp4; codecs="avc1.42E01E"',
592 },
593 });
594 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
595 const separatorIndex = suffix.indexOf("/");
596
597 expect(
598 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
599 ).toEqual({
600 kind: "file",
601 path: attachmentPath,
602 fileName: "demo.mp4",
603 mimeType: "video/mp4",
604 });
605 }).pipe(Effect.provide(testLayer)),
606 );
607 it.effect("issues signed native application icon capabilities", () =>
608 Effect.gen(function* () {
609 const result = yield* issueAssetUrl({
610 resource: {
611 _tag: "native-app-icon",
612 app: { _tag: "app-id", appId: "com.example.Editor" },
613 },
614 });
615
616 expect(result.relativeUrl).toMatch(
617 new RegExp(`^${ASSET_ROUTE_PREFIX}/[^/]+/native-app-icon\\.png$`, "u"),
618 );
619 expect(result.expiresAt).toBeGreaterThan(0);
620 }).pipe(Effect.provide(testLayer)),
621 );
622
623 it.effect("serves document attachments inline when a viewer requests it", () =>
624 Effect.gen(function* () {
625 const config = yield* ServerConfig.ServerConfig;
626 const fileSystem = yield* FileSystem.FileSystem;
627 const path = yield* Path.Path;
628 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-pdf";
629 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
630 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
631 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
632
633 const result = yield* issueAssetUrl({
634 resource: {
635 _tag: "attachment",
636 attachmentId,
637 fileName: "report.pdf",
638 mimeType: "application/pdf",
639 disposition: "inline",
640 },
641 });
642 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
643 const separatorIndex = suffix.indexOf("/");
644
645 expect(
646 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
647 ).toEqual({
648 kind: "file",
649 path: attachmentPath,
650 fileName: "report.pdf",
651 mimeType: "application/pdf",
652 });
653 }).pipe(Effect.provide(testLayer)),
654 );
655
656 it.effect("keeps inline requests for other attachment types as downloads", () =>
657 Effect.gen(function* () {
658 const config = yield* ServerConfig.ServerConfig;
659 const fileSystem = yield* FileSystem.FileSystem;
660 const path = yield* Path.Path;
661 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";
662 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);
663 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
664 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
665
666 const result = yield* issueAssetUrl({
667 resource: {
668 _tag: "attachment",
669 attachmentId,
670 fileName: "archive.zip",
671 mimeType: "text/html",
672 disposition: "inline",
673 },
674 });
675 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
676 const separatorIndex = suffix.indexOf("/");
677
678 expect(
679 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
680 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
681 }).pipe(Effect.provide(testLayer)),
682 );
683 it.effect("issues project favicon capabilities with a signed fallback", () =>
684 Effect.gen(function* () {
685 const fileSystem = yield* FileSystem.FileSystem;
686 const path = yield* Path.Path;
687 const root = yield* fileSystem.makeTempDirectoryScoped({
688 prefix: "t3-asset-favicon-",
689 });
690 const faviconPath = path.join(root, "favicon.svg");
691 const initialFavicon = "<svg>a</svg>";
692 const updatedFavicon = "<svg>b</svg>";
693 expect(updatedFavicon).toHaveLength(initialFavicon.length);
694 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
695 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
696
697 const faviconResult = yield* issueAssetUrl({
698 resource: { _tag: "project-favicon", cwd: root },
699 });
700 expect(faviconResult.sourcePath).toBe("favicon.svg");
701 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
702 expect(
703 yield* issueAssetUrl({
704 resource: { _tag: "project-favicon", cwd: root },
705 }),
706 ).toEqual(faviconResult);
707 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
708 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
709 expect(
710 yield* resolveAsset(
711 faviconSuffix.slice(0, faviconSeparatorIndex),
712 faviconSuffix.slice(faviconSeparatorIndex + 1),
713 ),
714 ).toEqual({ kind: "file", path: canonicalFaviconPath });
715
716 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
717 const updatedFaviconResult = yield* issueAssetUrl({
718 resource: { _tag: "project-favicon", cwd: root },
719 });
720 expect(
721 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
722 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
723
724 yield* fileSystem.remove(faviconPath);
725 const fallbackResult = yield* issueAssetUrl({
726 resource: { _tag: "project-favicon", cwd: root },
727 });
728 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
729 expect(fallbackResult.sourcePath).toBeUndefined();
730 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
731 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
732 expect(
733 yield* resolveAsset(
734 fallbackSuffix.slice(0, fallbackSeparatorIndex),
735 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
736 ),
737 ).toBeNull();
738 }).pipe(Effect.provide(testLayer)),
739 );
740
741 it.effect("issues project favicon capabilities for a saved override", () =>
742 Effect.gen(function* () {
743 const fileSystem = yield* FileSystem.FileSystem;
744 const path = yield* Path.Path;
745 const root = yield* fileSystem.makeTempDirectoryScoped({
746 prefix: "t3-asset-favicon-override-",
747 });
748 yield* fileSystem.makeDirectory(path.join(root, "brand"));
749 yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
750 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
751
752 const result = yield* issueAssetUrl({
753 resource: { _tag: "project-favicon", cwd: root },
754 projectFaviconPath: "brand/custom.svg",
755 });
756
757 expect(result.sourcePath).toBe(path.join("brand", "custom.svg"));
758 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
759 }).pipe(Effect.provide(testLayer)),
760 );
761
762 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
763 Effect.gen(function* () {
764 const fileSystem = yield* FileSystem.FileSystem;
765 const path = yield* Path.Path;
766 const root = yield* fileSystem.makeTempDirectoryScoped({
767 prefix: "t3-asset-favicon-workspace-",
768 });
769 const pictures = yield* fileSystem.makeTempDirectoryScoped({
770 prefix: "t3-asset-favicon-pictures-",
771 });
772 const externalPath = path.join(pictures, "custom.png");
773 const siblingPath = path.join(pictures, "sibling.png");
774 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
775 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
776 const canonicalPath = yield* fileSystem.realPath(externalPath);
777 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
778
779 const result = yield* issueAssetUrl({
780 resource: { _tag: "project-favicon", cwd: root },
781 projectFaviconPath: externalPath,
782 });
783 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
784 const separatorIndex = suffix.indexOf("/");
785
786 expect(result.sourcePath).toBe(externalPath);
787 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
788 expect(
789 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
790 ).toEqual({ kind: "file", path: canonicalPath });
791 const tamperedSuffixResult = yield* resolveAsset(
792 suffix.slice(0, separatorIndex),
793 "sibling.png",
794 );
795 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
796 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
797 }).pipe(Effect.provide(testLayer)),
798 );
799
800 it.effect("ignores a client favicon path hint", () =>
801 Effect.gen(function* () {
802 const fileSystem = yield* FileSystem.FileSystem;
803 const path = yield* Path.Path;
804 const root = yield* fileSystem.makeTempDirectoryScoped({
805 prefix: "t3-asset-favicon-hint-",
806 });
807 yield* fileSystem.makeDirectory(path.join(root, "brand"));
808 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
809 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
810
811 const result = yield* issueAssetUrl({
812 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
813 projectFaviconPath: "brand/saved.svg",
814 });
815
816 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
817 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
818 }).pipe(Effect.provide(testLayer)),
819 );
820
821 it.effect("keeps automatic favicon resolution separate from a saved override", () =>
822 Effect.gen(function* () {
823 const fileSystem = yield* FileSystem.FileSystem;
824 const path = yield* Path.Path;
825 const root = yield* fileSystem.makeTempDirectoryScoped({
826 prefix: "t3-asset-favicon-automatic-",
827 });
828 yield* fileSystem.makeDirectory(path.join(root, "brand"));
829 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
830 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
831
832 const result = yield* issueAssetUrl({
833 resource: { _tag: "project-favicon", cwd: root },
834 });
835
836 expect(result.sourcePath).toBe("favicon.svg");
837 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
838 }).pipe(Effect.provide(testLayer)),
839 );
840
841 it.effect("rejects a resolved project favicon with a non-image extension", () =>
842 Effect.gen(function* () {
843 const fileSystem = yield* FileSystem.FileSystem;
844 const path = yield* Path.Path;
845 const root = yield* fileSystem.makeTempDirectoryScoped({
846 prefix: "t3-asset-favicon-type-",
847 });
848 yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
849
850 const error = yield* issueAssetUrl({
851 resource: { _tag: "project-favicon", cwd: root },
852 projectFaviconPath: "secret.txt",
853 }).pipe(Effect.flip);
854
855 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
856 }).pipe(Effect.provide(testLayer)),
857 );
858
859 it.effect("buckets project favicon expiry after content hashing", () =>
860 Effect.gen(function* () {
861 const crypto = yield* Crypto.Crypto;
862 const fileSystem = yield* FileSystem.FileSystem;
863 const path = yield* Path.Path;
864 const root = yield* fileSystem.makeTempDirectoryScoped({
865 prefix: "t3-asset-favicon-expiry-",
866 });
867 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
868
869 const bucketMs = 30 * 60 * 1000;
870 yield* TestClock.setTime(bucketMs - 1);
871 const crossingCrypto = Crypto.make({
872 randomBytes: (size) => new Uint8Array(size),
873 digest: (algorithm, data) =>
874 TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
875 });
876 const result = yield* issueAssetUrl({
877 resource: { _tag: "project-favicon", cwd: root },
878 }).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
879
880 expect(result.expiresAt).toBe(3 * bucketMs);
881 }).pipe(Effect.provide(testLayer)),
882 );
883
884 it.effect("preserves structured project favicon resolution causes", () =>
885 Effect.gen(function* () {
886 const fileSystem = yield* FileSystem.FileSystem;
887 const root = yield* fileSystem.makeTempDirectoryScoped({
888 prefix: "t3-asset-favicon-error-",
889 });
890 const platformCause = PlatformError.systemError({
891 _tag: "PermissionDenied",
892 module: "FileSystem",
893 method: "stat",
894 });
895 const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
896 operation: "stat-candidate",
897 workspaceRoot: root,
898 relativePath: "favicon.svg",
899 cause: platformCause,
900 });
901 const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
902 resolvePath: () => Effect.fail(resolutionCause),
903 });
904
905 const error = yield* issueAssetUrl({
906 resource: { _tag: "project-favicon", cwd: root },
907 }).pipe(
908 Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
909 Effect.flip,
910 );
911
912 expect(error.message).toBe("Failed to resolve project favicon.");
913 expect(error._tag).toBe("AssetProjectFaviconResolutionError");
914 expect(error.cause).toBe(resolutionCause);
915 }).pipe(Effect.provide(testLayer)),
916 );
917});