Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
3import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
4import { describe, expect, it } from "@effect/vitest";
5import * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as TestClock from "effect/testing/TestClock";
12
13import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
14import * as ServerConfig from "../config.ts";
15import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
16import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
17import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
18import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
19
20const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
21 prefix: "t3-asset-access-test-",
22});
23const testLayer = Layer.mergeAll(
24 configLayer,
25 WorkspacePaths.layer,
26 ProjectFaviconResolver.layer.pipe(
27 Layer.provide(WorkspacePaths.layer),
28 Layer.provide(T3ProjectFileLoader.layer),
29 ),
30 ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
31).pipe(Layer.provideMerge(NodeServices.layer));
32
33describe("AssetAccess", () => {
34 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
35 Effect.gen(function* () {
36 const fileSystem = yield* FileSystem.FileSystem;
37 const path = yield* Path.Path;
38 const root = yield* fileSystem.makeTempDirectoryScoped({
39 prefix: "t3-asset-workspace-",
40 });
41 const htmlPath = path.join(root, "report.html");
42 const cssPath = path.join(root, "report.css");
43 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
44 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
45 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
46 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
47 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
48
49 const result = yield* issueAssetUrl({
50 resource: {
51 _tag: "workspace-file",
52 threadId: ThreadId.make("thread-1"),
53 path: htmlPath,
54 },
55 workspaceRoot: root,
56 });
57 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
58 const separatorIndex = suffix.indexOf("/");
59 const token = suffix.slice(0, separatorIndex);
60
61 expect(yield* resolveAsset(token, "report.html")).toEqual({
62 kind: "file",
63 path: canonicalHtmlPath,
64 });
65 expect(yield* resolveAsset(token, "report.css")).toEqual({
66 kind: "file",
67 path: canonicalCssPath,
68 });
69 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
70 expect(yield* resolveAsset(token, ".env")).toBeNull();
71 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
72 }).pipe(Effect.provide(testLayer)),
73 );
74
75 it.effect("rejects workspace files outside the authorized root", () =>
76 Effect.gen(function* () {
77 const fileSystem = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const root = yield* fileSystem.makeTempDirectoryScoped({
80 prefix: "t3-asset-root-",
81 });
82 const outside = yield* fileSystem.makeTempDirectoryScoped({
83 prefix: "t3-asset-outside-",
84 });
85 const htmlPath = path.join(outside, "report.html");
86 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
87
88 const error = yield* issueAssetUrl({
89 resource: {
90 _tag: "workspace-file",
91 threadId: ThreadId.make("thread-1"),
92 path: htmlPath,
93 },
94 workspaceRoot: root,
95 }).pipe(Effect.flip);
96 expect(error.message).toBe("Workspace file path must be relative to the project root.");
97 expect(error).toMatchObject({
98 _tag: "AssetWorkspacePathValidationError",
99 resource: {
100 _tag: "workspace-file",
101 threadId: "thread-1",
102 path: htmlPath,
103 },
104 });
105 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
106 }).pipe(Effect.provide(testLayer)),
107 );
108
109 it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
110 Effect.gen(function* () {
111 const fileSystem = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const root = yield* fileSystem.makeTempDirectoryScoped({
114 prefix: "t3-asset-permission-root-",
115 });
116 const htmlPath = path.join(root, "report.html");
117 yield* fileSystem.writeFileString(htmlPath, "<p>report</p>");
118 const cause = PlatformError.systemError({
119 _tag: "PermissionDenied",
120 module: "FileSystem",
121 method: "realPath",
122 pathOrDescriptor: htmlPath,
123 });
124 const failingFileSystem = FileSystem.FileSystem.of({
125 ...fileSystem,
126 realPath: () => Effect.fail(cause),
127 });
128
129 const error = yield* issueAssetUrl({
130 resource: {
131 _tag: "workspace-file",
132 threadId: ThreadId.make("thread-1"),
133 path: htmlPath,
134 },
135 workspaceRoot: root,
136 }).pipe(Effect.provideService(FileSystem.FileSystem, failingFileSystem), Effect.flip);
137
138 expect(error.message).toBe("Failed to inspect the workspace asset.");
139 expect(error).toMatchObject({
140 _tag: "AssetWorkspaceAssetInspectionError",
141 resource: {
142 _tag: "workspace-file",
143 threadId: "thread-1",
144 path: htmlPath,
145 },
146 });
147 expect(error.cause).toBe(cause);
148 }).pipe(Effect.provide(testLayer)),
149 );
150
151 it.effect("issues exact workspace URLs for image previews", () =>
152 Effect.gen(function* () {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const root = yield* fileSystem.makeTempDirectoryScoped({
156 prefix: "t3-asset-image-workspace-",
157 });
158 const assetsDirectory = path.join(root, "assets");
159 const imagePath = path.join(assetsDirectory, "icon.png");
160 const siblingPath = path.join(assetsDirectory, "other.png");
161 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
162 yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
163 yield* fileSystem.writeFile(siblingPath, new Uint8Array([137, 80, 78, 71]));
164 const canonicalImagePath = yield* fileSystem.realPath(imagePath);
165
166 const result = yield* issueAssetUrl({
167 resource: {
168 _tag: "workspace-file",
169 threadId: ThreadId.make("thread-1"),
170 path: imagePath,
171 },
172 workspaceRoot: root,
173 });
174 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
175 const separatorIndex = suffix.indexOf("/");
176 const token = suffix.slice(0, separatorIndex);
177
178 expect(yield* resolveAsset(token, "icon.png")).toEqual({
179 kind: "file",
180 path: canonicalImagePath,
181 });
182 expect(yield* resolveAsset(token, "other.png")).toBeNull();
183 expect(yield* resolveAsset(token, "../icon.png")).toBeNull();
184 }).pipe(Effect.provide(testLayer)),
185 );
186
187 it.effect("issues exact attachment capabilities by attachment id", () =>
188 Effect.gen(function* () {
189 const config = yield* ServerConfig.ServerConfig;
190 const fileSystem = yield* FileSystem.FileSystem;
191 const path = yield* Path.Path;
192 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
193 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
194 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
195 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
196
197 const result = yield* issueAssetUrl({
198 resource: { _tag: "attachment", attachmentId },
199 });
200 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
201 const separatorIndex = suffix.indexOf("/");
202 const token = suffix.slice(0, separatorIndex);
203
204 expect(yield* resolveAsset(token, "ignored.png")).toEqual({
205 kind: "file",
206 path: attachmentPath,
207 });
208 }).pipe(Effect.provide(testLayer)),
209 );
210
211 it.effect("issues project favicon capabilities with a signed fallback", () =>
212 Effect.gen(function* () {
213 const fileSystem = yield* FileSystem.FileSystem;
214 const path = yield* Path.Path;
215 const root = yield* fileSystem.makeTempDirectoryScoped({
216 prefix: "t3-asset-favicon-",
217 });
218 const faviconPath = path.join(root, "favicon.svg");
219 const initialFavicon = "<svg>a</svg>";
220 const updatedFavicon = "<svg>b</svg>";
221 expect(updatedFavicon).toHaveLength(initialFavicon.length);
222 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
223 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
224
225 const faviconResult = yield* issueAssetUrl({
226 resource: { _tag: "project-favicon", cwd: root },
227 });
228 expect(faviconResult.sourcePath).toBe("favicon.svg");
229 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
230 expect(
231 yield* issueAssetUrl({
232 resource: { _tag: "project-favicon", cwd: root },
233 }),
234 ).toEqual(faviconResult);
235 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
236 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
237 expect(
238 yield* resolveAsset(
239 faviconSuffix.slice(0, faviconSeparatorIndex),
240 faviconSuffix.slice(faviconSeparatorIndex + 1),
241 ),
242 ).toEqual({ kind: "file", path: canonicalFaviconPath });
243
244 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
245 const updatedFaviconResult = yield* issueAssetUrl({
246 resource: { _tag: "project-favicon", cwd: root },
247 });
248 expect(
249 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
250 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
251
252 yield* fileSystem.remove(faviconPath);
253 const fallbackResult = yield* issueAssetUrl({
254 resource: { _tag: "project-favicon", cwd: root },
255 });
256 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
257 expect(fallbackResult.sourcePath).toBeUndefined();
258 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
259 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
260 expect(
261 yield* resolveAsset(
262 fallbackSuffix.slice(0, fallbackSeparatorIndex),
263 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
264 ),
265 ).toBeNull();
266 }).pipe(Effect.provide(testLayer)),
267 );
268
269 it.effect("issues project favicon capabilities for a saved override", () =>
270 Effect.gen(function* () {
271 const fileSystem = yield* FileSystem.FileSystem;
272 const path = yield* Path.Path;
273 const root = yield* fileSystem.makeTempDirectoryScoped({
274 prefix: "t3-asset-favicon-override-",
275 });
276 yield* fileSystem.makeDirectory(path.join(root, "brand"));
277 yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
278 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
279
280 const result = yield* issueAssetUrl({
281 resource: { _tag: "project-favicon", cwd: root },
282 projectFaviconPath: "brand/custom.svg",
283 });
284
285 expect(result.sourcePath).toBe("brand/custom.svg");
286 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
287 }).pipe(Effect.provide(testLayer)),
288 );
289
290 it.effect("ignores a client favicon path hint", () =>
291 Effect.gen(function* () {
292 const fileSystem = yield* FileSystem.FileSystem;
293 const path = yield* Path.Path;
294 const root = yield* fileSystem.makeTempDirectoryScoped({
295 prefix: "t3-asset-favicon-hint-",
296 });
297 yield* fileSystem.makeDirectory(path.join(root, "brand"));
298 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
299 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
300
301 const result = yield* issueAssetUrl({
302 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
303 projectFaviconPath: "brand/saved.svg",
304 });
305
306 expect(result.sourcePath).toBe("brand/saved.svg");
307 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
308 }).pipe(Effect.provide(testLayer)),
309 );
310
311 it.effect("keeps automatic favicon resolution separate from a saved override", () =>
312 Effect.gen(function* () {
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const root = yield* fileSystem.makeTempDirectoryScoped({
316 prefix: "t3-asset-favicon-automatic-",
317 });
318 yield* fileSystem.makeDirectory(path.join(root, "brand"));
319 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
320 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
321
322 const result = yield* issueAssetUrl({
323 resource: { _tag: "project-favicon", cwd: root },
324 });
325
326 expect(result.sourcePath).toBe("favicon.svg");
327 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
328 }).pipe(Effect.provide(testLayer)),
329 );
330
331 it.effect("rejects a resolved project favicon with a non-image extension", () =>
332 Effect.gen(function* () {
333 const fileSystem = yield* FileSystem.FileSystem;
334 const path = yield* Path.Path;
335 const root = yield* fileSystem.makeTempDirectoryScoped({
336 prefix: "t3-asset-favicon-type-",
337 });
338 yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
339
340 const error = yield* issueAssetUrl({
341 resource: { _tag: "project-favicon", cwd: root },
342 projectFaviconPath: "secret.txt",
343 }).pipe(Effect.flip);
344
345 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
346 }).pipe(Effect.provide(testLayer)),
347 );
348
349 it.effect("buckets project favicon expiry after content hashing", () =>
350 Effect.gen(function* () {
351 const crypto = yield* Crypto.Crypto;
352 const fileSystem = yield* FileSystem.FileSystem;
353 const path = yield* Path.Path;
354 const root = yield* fileSystem.makeTempDirectoryScoped({
355 prefix: "t3-asset-favicon-expiry-",
356 });
357 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
358
359 const bucketMs = 30 * 60 * 1000;
360 yield* TestClock.setTime(bucketMs - 1);
361 const crossingCrypto = Crypto.make({
362 randomBytes: (size) => new Uint8Array(size),
363 digest: (algorithm, data) =>
364 TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
365 });
366 const result = yield* issueAssetUrl({
367 resource: { _tag: "project-favicon", cwd: root },
368 }).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
369
370 expect(result.expiresAt).toBe(3 * bucketMs);
371 }).pipe(Effect.provide(testLayer)),
372 );
373
374 it.effect("preserves structured project favicon resolution causes", () =>
375 Effect.gen(function* () {
376 const fileSystem = yield* FileSystem.FileSystem;
377 const root = yield* fileSystem.makeTempDirectoryScoped({
378 prefix: "t3-asset-favicon-error-",
379 });
380 const platformCause = PlatformError.systemError({
381 _tag: "PermissionDenied",
382 module: "FileSystem",
383 method: "stat",
384 });
385 const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
386 operation: "stat-candidate",
387 workspaceRoot: root,
388 relativePath: "favicon.svg",
389 cause: platformCause,
390 });
391 const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
392 resolvePath: () => Effect.fail(resolutionCause),
393 });
394
395 const error = yield* issueAssetUrl({
396 resource: { _tag: "project-favicon", cwd: root },
397 }).pipe(
398 Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
399 Effect.flip,
400 );
401
402 expect(error.message).toBe("Failed to resolve project favicon.");
403 expect(error._tag).toBe("AssetProjectFaviconResolutionError");
404 expect(error.cause).toBe(resolutionCause);
405 }).pipe(Effect.provide(testLayer)),
406 );
407});