Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.test.ts

941 lines40.3 KB

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