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