Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { 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.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
229 expect(
230 yield* issueAssetUrl({
231 resource: { _tag: "project-favicon", cwd: root },
232 }),
233 ).toEqual(faviconResult);
234 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
235 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
236 expect(
237 yield* resolveAsset(
238 faviconSuffix.slice(0, faviconSeparatorIndex),
239 faviconSuffix.slice(faviconSeparatorIndex + 1),
240 ),
241 ).toEqual({ kind: "file", path: canonicalFaviconPath });
242
243 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
244 const updatedFaviconResult = yield* issueAssetUrl({
245 resource: { _tag: "project-favicon", cwd: root },
246 });
247 expect(
248 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
249 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
250
251 yield* fileSystem.remove(faviconPath);
252 const fallbackResult = yield* issueAssetUrl({
253 resource: { _tag: "project-favicon", cwd: root },
254 });
255 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
256 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
257 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
258 expect(
259 yield* resolveAsset(
260 fallbackSuffix.slice(0, fallbackSeparatorIndex),
261 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
262 ),
263 ).toBeNull();
264 }).pipe(Effect.provide(testLayer)),
265 );
266
267 it.effect("buckets project favicon expiry after content hashing", () =>
268 Effect.gen(function* () {
269 const crypto = yield* Crypto.Crypto;
270 const fileSystem = yield* FileSystem.FileSystem;
271 const path = yield* Path.Path;
272 const root = yield* fileSystem.makeTempDirectoryScoped({
273 prefix: "t3-asset-favicon-expiry-",
274 });
275 yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg />");
276
277 const bucketMs = 30 * 60 * 1000;
278 yield* TestClock.setTime(bucketMs - 1);
279 const crossingCrypto = Crypto.make({
280 randomBytes: (size) => new Uint8Array(size),
281 digest: (algorithm, data) =>
282 TestClock.adjust("2 millis").pipe(Effect.andThen(crypto.digest(algorithm, data))),
283 });
284 const result = yield* issueAssetUrl({
285 resource: { _tag: "project-favicon", cwd: root },
286 }).pipe(Effect.provideService(Crypto.Crypto, crossingCrypto));
287
288 expect(result.expiresAt).toBe(3 * bucketMs);
289 }).pipe(Effect.provide(testLayer)),
290 );
291
292 it.effect("preserves structured project favicon resolution causes", () =>
293 Effect.gen(function* () {
294 const fileSystem = yield* FileSystem.FileSystem;
295 const root = yield* fileSystem.makeTempDirectoryScoped({
296 prefix: "t3-asset-favicon-error-",
297 });
298 const platformCause = PlatformError.systemError({
299 _tag: "PermissionDenied",
300 module: "FileSystem",
301 method: "stat",
302 });
303 const resolutionCause = new ProjectFaviconResolver.ProjectFaviconResolutionError({
304 operation: "stat-candidate",
305 workspaceRoot: root,
306 relativePath: "favicon.svg",
307 cause: platformCause,
308 });
309 const resolver = ProjectFaviconResolver.ProjectFaviconResolver.of({
310 resolvePath: () => Effect.fail(resolutionCause),
311 });
312
313 const error = yield* issueAssetUrl({
314 resource: { _tag: "project-favicon", cwd: root },
315 }).pipe(
316 Effect.provideService(ProjectFaviconResolver.ProjectFaviconResolver, resolver),
317 Effect.flip,
318 );
319
320 expect(error.message).toBe("Failed to resolve project favicon.");
321 expect(error._tag).toBe("AssetProjectFaviconResolutionError");
322 expect(error.cause).toBe(resolutionCause);
323 }).pipe(Effect.provide(testLayer)),
324 );
325});