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

AssetAccess.test.ts

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