Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 AssetPreviewTypeValidationError,
5 AssetProjectFaviconInspectionError,
6 AssetProjectFaviconNotFoundError,
7 AssetProjectFaviconResolutionError,
8 AssetSigningKeyLoadError,
9 AssetWorkspaceAssetInspectionError,
10 AssetWorkspaceAssetNotFoundError,
11 AssetWorkspaceContextNotFoundError,
12 AssetWorkspacePathValidationError,
13 AssetWorkspaceResolutionError,
14 AssetWorkspaceRootNormalizationError,
15} from "@t3tools/contracts";
16import {
17 hostPreviewMimeTypeFromExtension,
18 isWorkspaceImagePreviewPath,
19 isWorkspacePreviewEntryPath,
20 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
21 WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
22} from "@t3tools/shared/filePreview";
23import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
24import * as Clock from "effect/Clock";
25import * as Crypto from "effect/Crypto";
26import * as Effect from "effect/Effect";
27import * as Encoding from "effect/Encoding";
28import * as FileSystem from "effect/FileSystem";
29import * as Option from "effect/Option";
30import * as Path from "effect/Path";
31import * as PlatformError from "effect/PlatformError";
32import * as Schema from "effect/Schema";
33
34import {
35 base64UrlDecodeUtf8,
36 base64UrlEncode,
37 signPayload,
38 timingSafeEqualBase64Url,
39} from "../auth/utils.ts";
40import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
41import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
42import * as ServerConfig from "../config.ts";
43import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
44import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
45import { openMediaFile, type OpenMediaFile } from "./MediaFile.ts";
46
47export const ASSET_ROUTE_PREFIX = "/api/assets";
48
49const SIGNING_SECRET_NAME = "asset-access-signing-key";
50const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
51const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
52const PROJECT_FAVICON_VERSION_PREFIX = "v";
53const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
54// Extensions a document viewer may request inline. The extension comes from
55// the attachment id the server assigned, never from the client's mime type.
56const INLINE_DOCUMENT_EXTENSIONS = new Set(["pdf", "html", "htm"]);
57const INLINE_DOCUMENT_MIME_TYPES: Record<string, string> = {
58 pdf: "application/pdf",
59 html: "text/html",
60 htm: "text/html",
61};
62const PREVIEW_ASSET_EXTENSIONS = new Set([
63 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
64 ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
65 ".css",
66 ".js",
67 ".mjs",
68 ".otf",
69 ".ttf",
70 ".woff",
71 ".woff2",
72]);
73
74const AssetClaimsSchema = Schema.Union([
75 Schema.Struct({
76 version: Schema.Literal(1),
77 kind: Schema.Literal("workspace-file"),
78 workspaceRoot: Schema.String,
79 baseRelativePath: Schema.String,
80 expiresAt: Schema.Number,
81 }),
82 Schema.Struct({
83 version: Schema.Literal(1),
84 kind: Schema.Literal("workspace-file-exact"),
85 workspaceRoot: Schema.String,
86 relativePath: Schema.String,
87 expiresAt: Schema.Number,
88 }),
89 Schema.Struct({
90 version: Schema.Literal(1),
91 kind: Schema.Literal("media-file-exact"),
92 filePath: Schema.String,
93 device: Schema.String,
94 inode: Schema.String,
95 expiresAt: Schema.Number,
96 }),
97 Schema.Struct({
98 version: Schema.Literal(1),
99 kind: Schema.Literal("attachment"),
100 attachmentId: Schema.String,
101 /** Decided at mint time. Absent tokens (from before this field) serve
102 inline, which is only ever the image case. */
103 download: Schema.optionalKey(Schema.Boolean),
104 /** Display name and mime the caller supplied at mint time; drive the
105 download filename and Content-Type. */
106 fileName: Schema.optionalKey(Schema.String),
107 mimeType: Schema.optionalKey(Schema.String),
108 expiresAt: Schema.Number,
109 }),
110 Schema.Struct({
111 version: Schema.Literal(1),
112 kind: Schema.Literal("project-favicon"),
113 workspaceRoot: Schema.String,
114 relativePath: Schema.NullOr(Schema.String),
115 expiresAt: Schema.Number,
116 }),
117 Schema.Struct({
118 version: Schema.Literal(1),
119 kind: Schema.Literal("project-favicon-external"),
120 filePath: Schema.String,
121 expiresAt: Schema.Number,
122 }),
123]);
124type AssetClaims = typeof AssetClaimsSchema.Type;
125
126const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
127const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
128const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
129
130export type ResolvedAsset = {
131 readonly kind: "file";
132 readonly path: string;
133 readonly download?: boolean;
134 readonly fileName?: string;
135 readonly mimeType?: string;
136 readonly file?: OpenMediaFile;
137};
138
139function decodeClaims(encodedPayload: string): AssetClaims | null {
140 try {
141 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
142 } catch {
143 return null;
144 }
145}
146
147function decodeRelativePath(value: string): string | null {
148 try {
149 return decodeURIComponent(value);
150 } catch {
151 return null;
152 }
153}
154
155const optionOnNotFound = <A, R>(
156 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
157): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
158 effect.pipe(
159 Effect.map(Option.some),
160 Effect.catchTags({
161 PlatformError: (error) =>
162 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
163 }),
164 );
165
166const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
167 filePath: string,
168) {
169 const fileSystem = yield* FileSystem.FileSystem;
170 const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
171 if (Option.isNone(canonicalFile)) return null;
172
173 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
174 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
175});
176
177const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
178 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
179 const fileSystem = yield* FileSystem.FileSystem;
180 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
181 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
182 Effect.map(Option.some),
183 Effect.catchTags({
184 WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
185 }),
186 );
187 if (Option.isNone(resolved)) return null;
188
189 const [canonicalRoot, canonicalFile] = yield* Effect.all([
190 optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
191 optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
192 ]);
193 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
194
195 const path = yield* Path.Path;
196 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
197 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
198
199 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
200 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
201 },
202);
203
204const resolveCanonicalWorkspaceFileForRequest = (input: {
205 readonly workspaceRoot: string;
206 readonly relativePath: string;
207}) =>
208 resolveCanonicalWorkspaceFile(input).pipe(
209 Effect.tapError((cause) =>
210 Effect.logError("Failed to resolve canonical asset path.", {
211 workspaceRoot: input.workspaceRoot,
212 relativePath: input.relativePath,
213 cause,
214 }),
215 ),
216 Effect.orElseSucceed(() => null),
217 );
218
219export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
220 readonly resource: AssetResource;
221 readonly workspaceRoot?: string;
222 readonly projectFaviconPath?: string;
223}) {
224 const fileSystem = yield* FileSystem.FileSystem;
225 const path = yield* Path.Path;
226 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
227 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
228 let claims: AssetClaims;
229 let fileName: string;
230 let sourcePath: string | undefined;
231
232 switch (input.resource._tag) {
233 case "media-file": {
234 let requestedPath = input.resource.path;
235 if (!path.isAbsolute(requestedPath)) {
236 if (!input.workspaceRoot) {
237 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
238 }
239 const workspaceRoot = yield* workspacePaths
240 .normalizeWorkspaceRoot(input.workspaceRoot)
241 .pipe(
242 Effect.mapError(
243 (cause) =>
244 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
245 ),
246 );
247 requestedPath = path.resolve(workspaceRoot, requestedPath);
248 }
249 const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
250 Effect.mapError(
251 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
252 ),
253 );
254 if (!canonicalFile) {
255 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
256 }
257 if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
258 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
259 }
260 const identity = yield* openMediaFile(canonicalFile).pipe(
261 Effect.map((file) =>
262 file ? { device: file.info.dev.toString(), inode: file.info.ino.toString() } : null,
263 ),
264 Effect.scoped,
265 Effect.mapError(
266 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
267 ),
268 );
269 if (!identity) {
270 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
271 }
272 claims = {
273 version: 1,
274 kind: "media-file-exact",
275 filePath: canonicalFile,
276 ...identity,
277 expiresAt,
278 };
279 fileName = path.basename(canonicalFile);
280 break;
281 }
282 case "workspace-file": {
283 if (!input.workspaceRoot) {
284 return yield* new AssetWorkspaceContextNotFoundError({
285 resource: input.resource,
286 });
287 }
288 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
289 Effect.mapError(
290 (cause) =>
291 new AssetWorkspaceRootNormalizationError({
292 resource: input.resource,
293 cause,
294 }),
295 ),
296 );
297 const relativePath = path.isAbsolute(input.resource.path)
298 ? path.relative(workspaceRoot, input.resource.path)
299 : input.resource.path;
300 const resolved = yield* workspacePaths
301 .resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
302 .pipe(
303 Effect.mapError(
304 (cause) =>
305 new AssetWorkspacePathValidationError({
306 resource: input.resource,
307 cause,
308 }),
309 ),
310 );
311 if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
312 return yield* new AssetPreviewTypeValidationError({
313 resource: input.resource,
314 });
315 }
316 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
317 workspaceRoot,
318 relativePath: resolved.relativePath,
319 }).pipe(
320 Effect.mapError(
321 (cause) =>
322 new AssetWorkspaceAssetInspectionError({
323 resource: input.resource,
324 cause,
325 }),
326 ),
327 );
328 if (!canonicalFile) {
329 return yield* new AssetWorkspaceAssetNotFoundError({
330 resource: input.resource,
331 });
332 }
333 const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
334 Effect.mapError(
335 (cause) =>
336 new AssetWorkspaceResolutionError({
337 resource: input.resource,
338 cause,
339 }),
340 ),
341 );
342 claims = isWorkspaceImagePreviewPath(resolved.relativePath)
343 ? {
344 version: 1,
345 kind: "workspace-file-exact",
346 workspaceRoot: canonicalWorkspaceRoot,
347 relativePath: resolved.relativePath,
348 expiresAt,
349 }
350 : {
351 version: 1,
352 kind: "workspace-file",
353 workspaceRoot: canonicalWorkspaceRoot,
354 baseRelativePath: path.dirname(resolved.relativePath),
355 expiresAt,
356 };
357 fileName = path.basename(resolved.relativePath);
358 break;
359 }
360 case "attachment": {
361 const config = yield* ServerConfig.ServerConfig;
362 const attachmentPath = resolveAttachmentPathById({
363 attachmentsDir: config.attachmentsDir,
364 attachmentId: input.resource.attachmentId,
365 });
366 if (!attachmentPath) {
367 return yield* new AssetAttachmentNotFoundError({
368 resource: input.resource,
369 });
370 }
371 // Generic files carry their extension inside the attachment id (that
372 // shape resolves the on-disk path); images do not. Videos and images
373 // render inline. Other generic files download, unless a document viewer
374 // asked for inline and the stored extension is one a browser can show.
375 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
376 const isGenericFile = extension !== null;
377 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
378 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
379 const inlineDocumentMimeType =
380 input.resource.disposition === "inline" &&
381 extension !== null &&
382 INLINE_DOCUMENT_EXTENSIONS.has(extension)
383 ? INLINE_DOCUMENT_MIME_TYPES[extension]
384 : undefined;
385 claims = {
386 version: 1,
387 kind: "attachment",
388 attachmentId: input.resource.attachmentId,
389 ...(isGenericFile && !isVideo && inlineDocumentMimeType === undefined
390 ? { download: true }
391 : {}),
392 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
393 ...(inlineDocumentMimeType !== undefined
394 ? { mimeType: inlineDocumentMimeType }
395 : input.resource.mimeType !== undefined
396 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
397 : {}),
398 expiresAt,
399 };
400 fileName = input.resource.fileName ?? path.basename(attachmentPath);
401 break;
402 }
403 case "project-favicon": {
404 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
405 Effect.mapError(
406 (cause) =>
407 new AssetWorkspaceRootNormalizationError({
408 resource: input.resource,
409 cause,
410 }),
411 ),
412 );
413 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
414 const faviconPath = yield* faviconResolver
415 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
416 .pipe(
417 Effect.mapError(
418 (cause) =>
419 new AssetProjectFaviconResolutionError({
420 resource: input.resource,
421 cause,
422 }),
423 ),
424 );
425 const isExternalOverride =
426 faviconPath !== null &&
427 input.projectFaviconPath !== undefined &&
428 path.isAbsolute(input.projectFaviconPath) &&
429 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
430 const relativePath =
431 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
432 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
433 if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
434 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
435 }
436 sourcePath = sourceFaviconPath ?? undefined;
437 const canonicalFaviconPath = sourceFaviconPath
438 ? yield* (
439 isExternalOverride
440 ? resolveCanonicalFile(sourceFaviconPath)
441 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
442 ).pipe(
443 Effect.mapError(
444 (cause) =>
445 new AssetProjectFaviconInspectionError({
446 resource: input.resource,
447 cause,
448 }),
449 ),
450 )
451 : null;
452 if (sourceFaviconPath && !canonicalFaviconPath) {
453 return yield* new AssetProjectFaviconNotFoundError({
454 resource: input.resource,
455 });
456 }
457 claims =
458 isExternalOverride && canonicalFaviconPath
459 ? {
460 version: 1,
461 kind: "project-favicon-external",
462 filePath: canonicalFaviconPath,
463 expiresAt,
464 }
465 : {
466 version: 1,
467 kind: "project-favicon",
468 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
469 Effect.mapError(
470 (cause) =>
471 new AssetWorkspaceResolutionError({
472 resource: input.resource,
473 cause,
474 }),
475 ),
476 ),
477 relativePath,
478 expiresAt,
479 };
480 if (sourceFaviconPath && canonicalFaviconPath) {
481 const crypto = yield* Crypto.Crypto;
482 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
483 Effect.mapError(
484 (cause) =>
485 new AssetProjectFaviconInspectionError({
486 resource: input.resource,
487 cause,
488 }),
489 ),
490 );
491 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
492 Effect.map(Encoding.encodeHex),
493 Effect.mapError(
494 (cause) =>
495 new AssetProjectFaviconInspectionError({
496 resource: input.resource,
497 cause,
498 }),
499 ),
500 );
501 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
502 } else {
503 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
504 }
505 break;
506 }
507 }
508
509 const secretStore = yield* ServerSecretStore.ServerSecretStore;
510 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
511 Effect.mapError(
512 (cause) =>
513 new AssetSigningKeyLoadError({
514 resource: input.resource,
515 cause,
516 }),
517 ),
518 );
519 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
520 const issuedAt = yield* Clock.currentTimeMillis;
521 expiresAt =
522 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
523 PROJECT_FAVICON_TOKEN_BUCKET_MS;
524 claims = { ...claims, expiresAt };
525 }
526 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
527 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
528 return {
529 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
530 expiresAt,
531 ...(sourcePath !== undefined ? { sourcePath } : {}),
532 };
533});
534
535export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
536 token: string,
537 relativePath: string,
538) {
539 const [encodedPayload, signature] = token.split(".");
540 if (!encodedPayload || !signature) return null;
541
542 const secretStore = yield* ServerSecretStore.ServerSecretStore;
543 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
544 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
545 Effect.orElseSucceed(() => null),
546 );
547 if (!signingSecret) return null;
548 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
549
550 const claims = decodeClaims(encodedPayload);
551 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
552
553 if (claims.kind === "attachment") {
554 const config = yield* ServerConfig.ServerConfig;
555 const attachmentPath = resolveAttachmentPathById({
556 attachmentsDir: config.attachmentsDir,
557 attachmentId: claims.attachmentId,
558 });
559 if (!attachmentPath) return null;
560 const fileSystem = yield* FileSystem.FileSystem;
561 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
562 Effect.tapError((cause) =>
563 Effect.logError("Failed to inspect attachment asset.", {
564 attachmentId: claims.attachmentId,
565 path: attachmentPath,
566 cause,
567 }),
568 ),
569 Effect.orElseSucceed(() => Option.none()),
570 );
571 return Option.isSome(info) && info.value.type === "File"
572 ? ({
573 kind: "file",
574 path: attachmentPath,
575 ...(claims.download ? { download: true } : {}),
576 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
577 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
578 } satisfies ResolvedAsset)
579 : null;
580 }
581
582 if (claims.kind === "project-favicon") {
583 if (claims.relativePath === null) return null;
584 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
585 workspaceRoot: claims.workspaceRoot,
586 relativePath: claims.relativePath,
587 });
588 return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
589 }
590
591 if (claims.kind === "project-favicon-external") {
592 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
593 Effect.tapError((cause) =>
594 Effect.logError("Failed to resolve canonical asset path.", {
595 filePath: claims.filePath,
596 cause,
597 }),
598 ),
599 Effect.orElseSucceed(() => null),
600 );
601 return faviconPath === claims.filePath
602 ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
603 : null;
604 }
605
606 const decodedPath = decodeRelativePath(relativePath);
607 if (decodedPath === null) return null;
608 const path = yield* Path.Path;
609 if (claims.kind === "media-file-exact") {
610 if (decodedPath !== path.basename(claims.filePath)) return null;
611 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
612 Effect.tapError((cause) =>
613 Effect.logError("Failed to resolve canonical media path.", {
614 filePath: claims.filePath,
615 cause,
616 }),
617 ),
618 Effect.orElseSucceed(() => null),
619 );
620 if (canonicalFile !== claims.filePath) return null;
621 const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
622 if (!mimeType) return null;
623 const file = yield* openMediaFile(canonicalFile, claims).pipe(
624 Effect.tapError((cause) =>
625 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
626 ),
627 Effect.orElseSucceed(() => null),
628 );
629 return file
630 ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
631 : null;
632 }
633 if (claims.kind === "workspace-file-exact") {
634 if (decodedPath !== path.basename(claims.relativePath)) return null;
635 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
636 workspaceRoot: claims.workspaceRoot,
637 relativePath: claims.relativePath,
638 });
639 return exactWorkspaceFile
640 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
641 : null;
642 }
643 const segments = decodedPath.split(/[\\/]/);
644 if (
645 decodedPath.length === 0 ||
646 decodedPath.includes("\0") ||
647 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
648 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
649 ) {
650 return null;
651 }
652 const joinedRelativePath =
653 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
654 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
655 workspaceRoot: claims.workspaceRoot,
656 relativePath: joinedRelativePath,
657 });
658 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
659});