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