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