Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.ts

639 lines22.7 KB

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