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