Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 AssetSourceControlMediaUrlValidationError,
5 AssetPreviewTypeValidationError,
6 AssetProjectFaviconInspectionError,
7 AssetProjectFaviconNotFoundError,
8 AssetProjectFaviconResolutionError,
9 AssetSigningKeyLoadError,
10 AssetWorkspaceAssetInspectionError,
11 AssetWorkspaceAssetNotFoundError,
12 AssetWorkspaceContextNotFoundError,
13 AssetWorkspacePathValidationError,
14 AssetWorkspaceResolutionError,
15 AssetWorkspaceRootNormalizationError,
16 SOURCE_CONTROL_MEDIA_ASSET,
17 ThreadId,
18 NativeAppIconReference,
19 TurnItemId,
20 EnvironmentThemeId,
21} from "@t3tools/contracts";
22import {
23 hostPreviewMimeTypeFromExtension,
24 isWorkspaceAudioPreviewPath,
25 isWorkspacePreviewEntryPath,
26 isWorkspaceVideoPreviewPath,
27 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
28} from "@t3tools/shared/filePreview";
29import {
30 IMAGE_DIMENSIONS_HEADER_BYTES,
31 readImageDimensions,
32 type ImageDimensions,
33} from "@t3tools/shared/imageDimensions";
34import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
35import {
36 isProjectFaviconPath,
37 PROJECT_FAVICON_FALLBACK_MARKER,
38} from "@t3tools/shared/projectFavicon";
39import { isNetworkPath } from "@t3tools/shared/path";
40import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
41import * as Clock from "effect/Clock";
42import * as Digest from "effect/crypto/Digest";
43import * as Effect from "effect/Effect";
44import * as Hex from "effect/encoding/Hex";
45import * as FileSystem from "effect/FileSystem";
46import * as Option from "effect/Option";
47import * as Path from "effect/Path";
48import * as Schema from "effect/Schema";
49import * as Stream from "effect/Stream";
50
51import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
52import * as AssetSigner from "./AssetSigner.ts";
53import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
54import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
55import * as ServerConfig from "../config.ts";
56import { findThemeBackground } from "../environmentTheme.ts";
57import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
58import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
59import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
60import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
61import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
62import { toHostDrivePath } from "../workspace/hostDrivePath.ts";
63import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
64import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
65import { extractIcnsPng } from "./icns.ts";
66import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
67import * as HostProcess from "@t3tools/shared/HostProcess";
68
69export const ASSET_ROUTE_PREFIX = "/api/assets";
70
71const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
72const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
73const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
74const PROJECT_FAVICON_VERSION_PREFIX = "v";
75const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
76const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
77// Use server-assigned attachment extensions, never client MIME types.
78const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
79 svg: "image/svg+xml",
80 pdf: "application/pdf",
81 html: "text/html",
82 htm: "text/html",
83};
84const inlinePreviewMimeTypeForExtension = (extension: string) =>
85 INLINE_PREVIEW_MIME_TYPES[extension] ??
86 hostPreviewMimeTypeFromExtension(`.${extension}`) ??
87 undefined;
88const PREVIEW_ASSET_EXTENSIONS = new Set([
89 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
90 // Keep HTML dependency grants independent of newly supported file viewers.
91 ".avif",
92 ".gif",
93 ".ico",
94 ".jpeg",
95 ".jpg",
96 ".png",
97 ".svg",
98 ".webp",
99 ".m4v",
100 ".mp4",
101 ".ogv",
102 ".webm",
103 ".aac",
104 ".flac",
105 ".m4a",
106 ".mp3",
107 ".oga",
108 ".ogg",
109 ".opus",
110 ".wav",
111 ".css",
112 ".js",
113 ".mjs",
114 ".otf",
115 ".ttf",
116 ".woff",
117 ".woff2",
118]);
119
120const isPreviewDependencyPath = (filePath: string, path: Path.Path) =>
121 filePath.length > 0 &&
122 !filePath.includes("\0") &&
123 !filePath.split(/[\\/]/).some((segment) => segment.startsWith(".")) &&
124 PREVIEW_ASSET_EXTENSIONS.has(path.extname(filePath).toLowerCase());
125
126const AssetClaimsSchema = Schema.Union([
127 Schema.Struct({
128 version: Schema.Literal(1),
129 kind: Schema.Literal("workspace-file"),
130 workspaceRoot: Schema.String,
131 baseRelativePath: Schema.String,
132 expiresAt: Schema.Number,
133 }),
134 Schema.Struct({
135 version: Schema.Literal(1),
136 kind: Schema.Literal("workspace-file-exact"),
137 workspaceRoot: Schema.String,
138 relativePath: Schema.String,
139 expiresAt: Schema.Number,
140 }),
141 Schema.Struct({
142 version: Schema.Literal(1),
143 kind: Schema.Literal("media-file-exact"),
144 filePath: Schema.String,
145 download: Schema.optionalKey(Schema.Boolean),
146 device: Schema.String,
147 inode: Schema.String,
148 expiresAt: Schema.Number,
149 }),
150 Schema.Struct({
151 version: Schema.Literal(1),
152 kind: Schema.Literal("attachment"),
153 attachmentId: Schema.String,
154 download: Schema.optionalKey(Schema.Boolean),
155 fileName: Schema.optionalKey(Schema.String),
156 mimeType: Schema.optionalKey(Schema.String),
157 renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
158 expiresAt: Schema.Number,
159 }),
160 Schema.Struct({
161 version: Schema.Literal(1),
162 kind: Schema.Literal("project-favicon"),
163 workspaceRoot: Schema.String,
164 relativePath: Schema.NullOr(Schema.String),
165 expiresAt: Schema.Number,
166 }),
167 Schema.Struct({
168 version: Schema.Literal(1),
169 kind: Schema.Literal("project-favicon-external"),
170 filePath: Schema.String,
171 expiresAt: Schema.Number,
172 }),
173 Schema.Struct({
174 version: Schema.Literal(1),
175 kind: Schema.Literal("native-app-icon"),
176 app: NativeAppIconReference,
177 expiresAt: Schema.Number,
178 }),
179 Schema.Struct({
180 version: Schema.Literal(1),
181 kind: Schema.Literal("environment-theme-background"),
182 themeId: EnvironmentThemeId,
183 expiresAt: Schema.Number,
184 }),
185 Schema.Struct({
186 version: Schema.Literal(1),
187 kind: Schema.Literal("tool-output-image"),
188 threadId: ThreadId,
189 itemId: TurnItemId,
190 index: Schema.Number,
191 expiresAt: Schema.Number,
192 }),
193 Schema.Struct({
194 version: Schema.Literal(1),
195 kind: Schema.Literal(SOURCE_CONTROL_MEDIA_ASSET),
196 /** A host's `fetchUrl`, narrowed at mint time; the signature is what keeps it there. */
197 url: Schema.String,
198 cwd: Schema.String,
199 repository: Schema.optionalKey(Schema.String),
200 expiresAt: Schema.Number,
201 }),
202]);
203type AssetClaims = typeof AssetClaimsSchema.Type;
204
205const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
206const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
207const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
208
209export type ResolvedAsset =
210 | {
211 readonly kind: "file";
212 readonly path: string;
213 readonly download?: boolean;
214 readonly fileName?: string;
215 readonly mimeType?: string;
216 readonly file?: OpenMediaFile;
217 readonly renderIntent?: "mcp-app" | "file-preview";
218 }
219 | {
220 readonly kind: "bytes";
221 readonly bytes: Uint8Array;
222 readonly mimeType: string;
223 }
224 | {
225 readonly kind: "source-control-media";
226 readonly url: string;
227 readonly cwd: string;
228 readonly repository?: string;
229 readonly expiresAt: number;
230 };
231
232function decodeClaims(encodedPayload: string): AssetClaims | null {
233 try {
234 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
235 } catch {
236 return null;
237 }
238}
239
240function decodeRelativePath(value: string): string | null {
241 try {
242 return decodeURIComponent(value);
243 } catch {
244 return null;
245 }
246}
247
248export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
249 const fileSystem = yield* FileSystem.FileSystem;
250 // Allow space for stored CSP tags, but bound reads if the attachment grows after minting.
251 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
252 const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
253 const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
254 if (size > limit) return null;
255 const bytes = new Uint8Array(size);
256 let position = 0;
257 for (const chunk of chunks) {
258 bytes.set(chunk, position);
259 position += chunk.byteLength;
260 }
261 return bytes;
262});
263
264const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
265 readonly threadId: ThreadId;
266 readonly itemId: TurnItemId;
267 readonly index: number;
268}) {
269 const orchestrator = yield* Orchestrator.OrchestratorV2;
270 const item = yield* orchestrator.getTurnItem(input);
271 const image =
272 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
273 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
274 ? null
275 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
276});
277
278// Browsers cannot draw .icns; serve its embedded PNG.
279const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* (
280 filePath: string,
281) {
282 if (!filePath.toLowerCase().endsWith(".icns")) {
283 return { kind: "file", path: filePath } satisfies ResolvedAsset;
284 }
285 const fileSystem = yield* FileSystem.FileSystem;
286 const bytes = yield* fileSystem.readFile(filePath).pipe(
287 Effect.tapError((cause) =>
288 Effect.logError("Failed to read project icon image.", { filePath, cause }),
289 ),
290 Effect.orElseSucceed(() => null),
291 );
292 const png = bytes ? extractIcnsPng(bytes, PROJECT_FAVICON_ICNS_MIN_SIZE) : null;
293 return png
294 ? ({ kind: "bytes", bytes: png, mimeType: "image/png" } satisfies ResolvedAsset)
295 : null;
296});
297
298const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
299 filePath: string,
300) {
301 const fileSystem = yield* FileSystem.FileSystem;
302 const canonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
303 fileSystem.realPath(filePath),
304 );
305 if (Option.isNone(canonicalFile)) return null;
306
307 const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
308 if (Option.isNone(info) || info.value.type !== "File") return null;
309 const isServerInternalPath = yield* makeIsServerInternalPath;
310 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
311});
312
313const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
314 function* (input: {
315 readonly workspaceRoot: string;
316 readonly relativePath: string;
317 readonly previewDependency?: true;
318 }) {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
321 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
322 Effect.asSome,
323 Effect.catchTags({
324 WorkspacePathOutsideRootError: () => Effect.succeedNone,
325 }),
326 );
327 if (Option.isNone(resolved)) return null;
328
329 const [canonicalRoot, canonicalFile] = yield* Effect.all([
330 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
331 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
332 ]);
333 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
334
335 const path = yield* Path.Path;
336 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
337 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
338
339 if (input.previewDependency && !isPreviewDependencyPath(relative, path)) return null;
340
341 const info = yield* ProjectFaviconResolver.optionOnNotFound(
342 fileSystem.stat(canonicalFile.value),
343 );
344 if (Option.isNone(info) || info.value.type !== "File") return null;
345 const isServerInternalPath = yield* makeIsServerInternalPath;
346 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
347 },
348);
349
350const resolveCanonicalWorkspaceFileForRequest = (input: {
351 readonly workspaceRoot: string;
352 readonly relativePath: string;
353 readonly previewDependency?: true;
354}) =>
355 resolveCanonicalWorkspaceFile(input).pipe(
356 Effect.tapError((cause) =>
357 Effect.logError("Failed to resolve canonical asset path.", {
358 workspaceRoot: input.workspaceRoot,
359 relativePath: input.relativePath,
360 cause,
361 }),
362 ),
363 Effect.orElseSucceed(() => null),
364 );
365
366const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
367
368const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
369 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
370 Effect.map(readImageDimensions),
371 Effect.orElseSucceed((): ImageDimensions | null => null),
372 );
373
374// Non-blocking open prevents swapped-in FIFOs from hanging the request.
375const readImageDimensionsFromHeader = (filePath: string) =>
376 openMediaFile(filePath).pipe(
377 Effect.flatMap((file) =>
378 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
379 ),
380 Effect.scoped,
381 Effect.orElseSucceed((): ImageDimensions | null => null),
382 );
383
384const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
385 function* (input: {
386 readonly requestedPath: string;
387 readonly expectedCanonicalPath?: string;
388 readonly workspaceRoot: string | undefined;
389 readonly resource: AssetResource;
390 readonly expiresAt: number;
391 }) {
392 const path = yield* Path.Path;
393 // Resolving a network path makes Windows sign in to its host with the
394 // user's NTLM credentials, so only the thread's own project may be on a share.
395 // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
396 // the resolved path this check approved.
397 const requestedPath = path.resolve(input.requestedPath);
398 if (
399 isNetworkPath(input.requestedPath) &&
400 (input.workspaceRoot === undefined ||
401 !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
402 ) {
403 return yield* new AssetWorkspaceAssetNotFoundError({
404 resource: input.resource,
405 checkedPath: input.requestedPath,
406 });
407 }
408 const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
409 Effect.mapError(
410 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
411 ),
412 );
413 // The workspace caller pins its containment-checked path; never follow a
414 // replacement symlink to a different file during this second resolution.
415 if (
416 !canonicalFile ||
417 (input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
418 ) {
419 return yield* new AssetWorkspaceAssetNotFoundError({
420 resource: input.resource,
421 checkedPath: input.requestedPath,
422 });
423 }
424 const download =
425 input.resource._tag === "media-file" && input.resource.disposition === "attachment";
426 if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
427 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
428 }
429 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
430 const opened = yield* openMediaFile(canonicalFile).pipe(
431 Effect.flatMap((file) =>
432 file === null
433 ? Effect.succeed(null)
434 : Effect.map(
435 wantsDimensions
436 ? readImageDimensionsFromOpenFile(canonicalFile, file)
437 : Effect.succeed(null),
438 (dimensions) => ({
439 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
440 fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
441 dimensions,
442 }),
443 ),
444 ),
445 Effect.scoped,
446 Effect.mapError(
447 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
448 ),
449 );
450 if (!opened) {
451 return yield* new AssetWorkspaceAssetNotFoundError({
452 resource: input.resource,
453 checkedPath: input.requestedPath,
454 });
455 }
456 return {
457 claims: {
458 version: 1 as const,
459 kind: "media-file-exact" as const,
460 filePath: canonicalFile,
461 ...(download ? { download: true } : {}),
462 ...opened.identity,
463 expiresAt: input.expiresAt,
464 },
465 fileName: path.basename(canonicalFile),
466 fileRevision: opened.fileRevision,
467 imageDimensions: opened.dimensions,
468 };
469 },
470);
471
472const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
473 function* (input: {
474 readonly workspaceRoot: string;
475 readonly requestedPath: string;
476 readonly resource: AssetResource;
477 readonly expiresAt: number;
478 }) {
479 const path = yield* Path.Path;
480 const fileSystem = yield* FileSystem.FileSystem;
481 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
482 const relativePath = path.isAbsolute(input.requestedPath)
483 ? path.relative(input.workspaceRoot, input.requestedPath)
484 : input.requestedPath;
485 const resolved = yield* workspacePaths
486 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
487 .pipe(
488 Effect.mapError(
489 (cause) =>
490 new AssetWorkspacePathValidationError({
491 resource: input.resource,
492 cause,
493 }),
494 ),
495 );
496 const isDraftMedia =
497 input.resource._tag === "draft-workspace-file" &&
498 (isWorkspaceAudioPreviewPath(resolved.relativePath) ||
499 isWorkspaceVideoPreviewPath(resolved.relativePath));
500 if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
501 return yield* new AssetPreviewTypeValidationError({
502 resource: input.resource,
503 });
504 }
505 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
506 workspaceRoot: input.workspaceRoot,
507 relativePath: resolved.relativePath,
508 }).pipe(
509 Effect.mapError(
510 (cause) =>
511 new AssetWorkspaceAssetInspectionError({
512 resource: input.resource,
513 cause,
514 }),
515 ),
516 );
517 if (!canonicalFile) {
518 return yield* new AssetWorkspaceAssetNotFoundError({
519 resource: input.resource,
520 });
521 }
522 if (isDraftMedia) {
523 return yield* finalizeAbsoluteMediaFileAsset({
524 ...input,
525 requestedPath: canonicalFile,
526 expectedCanonicalPath: canonicalFile,
527 });
528 }
529 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
530 Effect.mapError(
531 (cause) =>
532 new AssetWorkspaceResolutionError({
533 resource: input.resource,
534 cause,
535 }),
536 ),
537 );
538 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
539 path.extname(resolved.relativePath).toLowerCase(),
540 )
541 ? yield* readImageDimensionsFromHeader(canonicalFile)
542 : null;
543 return {
544 claims: !/\.html?$/i.test(resolved.relativePath)
545 ? {
546 version: 1 as const,
547 kind: "workspace-file-exact" as const,
548 workspaceRoot: canonicalWorkspaceRoot,
549 relativePath: resolved.relativePath,
550 expiresAt: input.expiresAt,
551 }
552 : {
553 version: 1 as const,
554 kind: "workspace-file" as const,
555 workspaceRoot: canonicalWorkspaceRoot,
556 baseRelativePath: path.dirname(resolved.relativePath),
557 expiresAt: input.expiresAt,
558 },
559 fileName: path.basename(resolved.relativePath),
560 imageDimensions,
561 fileRevision: undefined,
562 };
563 },
564);
565
566export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
567 readonly resource: AssetResource;
568 readonly workspaceRoot?: string;
569 readonly projectFaviconPath?: string;
570 /** Where a cloned project's checkout stands, while the clone tracker still knows it. */
571 readonly projectCheckout?: "pending" | "cloned";
572}) {
573 const fileSystem = yield* FileSystem.FileSystem;
574 const path = yield* Path.Path;
575 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
576 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
577 let claims: AssetClaims;
578 let fileName: string;
579 let sourcePath: string | undefined;
580 let imageDimensions: ImageDimensions | null = null;
581 let fileRevision: string | undefined;
582
583 switch (input.resource._tag) {
584 case "media-file": {
585 let requestedPath = expandHomePath(
586 yield* toHostDrivePath(input.resource.path),
587 yield* HostProcess.HomeDirectory,
588 );
589 if (!path.isAbsolute(requestedPath)) {
590 if (!input.workspaceRoot) {
591 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
592 }
593 const workspaceRoot = yield* workspacePaths
594 .normalizeWorkspaceRoot(input.workspaceRoot)
595 .pipe(
596 Effect.mapError(
597 (cause) =>
598 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
599 ),
600 );
601 requestedPath = path.resolve(workspaceRoot, requestedPath);
602 }
603 const finalized = yield* finalizeAbsoluteMediaFileAsset({
604 requestedPath,
605 workspaceRoot: input.workspaceRoot,
606 resource: input.resource,
607 expiresAt,
608 });
609 claims = finalized.claims;
610 fileName = finalized.fileName;
611 imageDimensions = finalized.imageDimensions;
612 fileRevision = finalized.fileRevision;
613 break;
614 }
615 case "workspace-file": {
616 if (!input.workspaceRoot) {
617 return yield* new AssetWorkspaceContextNotFoundError({
618 resource: input.resource,
619 });
620 }
621 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
622 Effect.mapError(
623 (cause) =>
624 new AssetWorkspaceRootNormalizationError({
625 resource: input.resource,
626 cause,
627 }),
628 ),
629 );
630 const finalized = yield* finalizeWorkspaceFileAsset({
631 workspaceRoot,
632 requestedPath: input.resource.path,
633 resource: input.resource,
634 expiresAt,
635 });
636 claims = finalized.claims;
637 fileName = finalized.fileName;
638 imageDimensions = finalized.imageDimensions;
639 break;
640 }
641 case "draft-workspace-file": {
642 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
643 const hostPath =
644 input.resource.path.startsWith("~/") || input.resource.path.startsWith("~\\")
645 ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
646 : yield* toHostDrivePath(input.resource.path);
647 if (path.isAbsolute(hostPath)) {
648 const finalized = yield* finalizeAbsoluteMediaFileAsset({
649 requestedPath: hostPath,
650 workspaceRoot: draftWorkspaceRoot,
651 resource: input.resource,
652 expiresAt,
653 });
654 claims = finalized.claims;
655 fileName = finalized.fileName;
656 imageDimensions = finalized.imageDimensions;
657 fileRevision = finalized.fileRevision;
658 break;
659 }
660 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
661 Effect.mapError(
662 (cause) =>
663 new AssetWorkspaceRootNormalizationError({
664 resource: input.resource,
665 cause,
666 }),
667 ),
668 );
669 const finalized = yield* finalizeWorkspaceFileAsset({
670 workspaceRoot,
671 requestedPath: input.resource.path,
672 resource: input.resource,
673 expiresAt,
674 });
675 claims = finalized.claims;
676 fileName = finalized.fileName;
677 imageDimensions = finalized.imageDimensions;
678 fileRevision = finalized.fileRevision;
679 break;
680 }
681 case "attachment": {
682 const config = yield* ServerConfig.ServerConfig;
683 const attachmentPath = resolveAttachmentPathById({
684 attachmentsDir: config.attachmentsDir,
685 attachmentId: input.resource.attachmentId,
686 });
687 if (!attachmentPath) {
688 return yield* new AssetAttachmentNotFoundError({
689 resource: input.resource,
690 });
691 }
692 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
693 const isGenericFile = extension !== null;
694 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
695 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
696 const inlinePreviewMimeType =
697 input.resource.disposition === "inline" && extension !== null
698 ? inlinePreviewMimeTypeForExtension(extension)
699 : undefined;
700 if (!isGenericFile) {
701 imageDimensions = yield* fileSystem.realPath(attachmentPath).pipe(
702 Effect.flatMap(readImageDimensionsFromHeader),
703 Effect.orElseSucceed(() => null),
704 );
705 }
706 claims = {
707 version: 1,
708 kind: "attachment",
709 attachmentId: input.resource.attachmentId,
710 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
711 ? { download: true }
712 : {}),
713 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
714 ...(inlinePreviewMimeType !== undefined
715 ? { mimeType: inlinePreviewMimeType }
716 : input.resource.mimeType !== undefined
717 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
718 : {}),
719 ...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
720 ? { renderIntent: "mcp-app" as const }
721 : {}),
722 expiresAt,
723 };
724 fileName = input.resource.fileName ?? path.basename(attachmentPath);
725 break;
726 }
727 case "project-favicon": {
728 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
729 Effect.mapError(
730 (cause) =>
731 new AssetWorkspaceRootNormalizationError({
732 resource: input.resource,
733 cause,
734 }),
735 ),
736 );
737 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
738 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
739 // Once it lands, a miss cached before (by enrichment) is stale too.
740 if (input.projectCheckout === "cloned") yield* faviconResolver.invalidate(workspaceRoot);
741 const faviconPath =
742 input.projectCheckout === "pending"
743 ? null
744 : yield* faviconResolver
745 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
746 .pipe(
747 Effect.mapError(
748 (cause) =>
749 new AssetProjectFaviconResolutionError({
750 resource: input.resource,
751 cause,
752 }),
753 ),
754 );
755 const isExternalOverride =
756 faviconPath !== null &&
757 input.projectFaviconPath !== undefined &&
758 path.isAbsolute(input.projectFaviconPath) &&
759 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
760 const relativePath =
761 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
762 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
763 if (sourceFaviconPath && !isProjectFaviconPath(sourceFaviconPath)) {
764 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
765 }
766 sourcePath = sourceFaviconPath ?? undefined;
767 const canonicalFaviconPath = sourceFaviconPath
768 ? yield* (
769 isExternalOverride
770 ? resolveCanonicalFile(sourceFaviconPath)
771 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
772 ).pipe(
773 Effect.mapError(
774 (cause) =>
775 new AssetProjectFaviconInspectionError({
776 resource: input.resource,
777 cause,
778 }),
779 ),
780 )
781 : null;
782 if (sourceFaviconPath && !canonicalFaviconPath) {
783 return yield* new AssetProjectFaviconNotFoundError({
784 resource: input.resource,
785 });
786 }
787 claims =
788 isExternalOverride && canonicalFaviconPath
789 ? {
790 version: 1,
791 kind: "project-favicon-external",
792 filePath: canonicalFaviconPath,
793 expiresAt,
794 }
795 : {
796 version: 1,
797 kind: "project-favicon",
798 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
799 Effect.mapError(
800 (cause) =>
801 new AssetWorkspaceResolutionError({
802 resource: input.resource,
803 cause,
804 }),
805 ),
806 ),
807 relativePath,
808 expiresAt,
809 };
810 if (sourceFaviconPath && canonicalFaviconPath) {
811 const digest = yield* Digest.Digest;
812 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
813 Effect.mapError(
814 (cause) =>
815 new AssetProjectFaviconInspectionError({
816 resource: input.resource,
817 cause,
818 }),
819 ),
820 );
821 const revision = yield* digest.digest(Digest.sha256, faviconBytes).pipe(
822 Effect.map(Hex.encode),
823 Effect.mapError(
824 (cause) =>
825 new AssetProjectFaviconInspectionError({
826 resource: input.resource,
827 cause,
828 }),
829 ),
830 );
831 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
832 } else {
833 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
834 }
835 break;
836 }
837 case "tool-output-image": {
838 const image = yield* readToolOutputImage(input.resource).pipe(
839 Effect.mapError(
840 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
841 ),
842 );
843 if (image === null) {
844 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
845 }
846 claims = {
847 version: 1,
848 kind: "tool-output-image",
849 threadId: input.resource.threadId,
850 itemId: input.resource.itemId,
851 index: input.resource.index,
852 expiresAt,
853 };
854 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
855 imageDimensions = readImageDimensions(image.bytes);
856 break;
857 }
858 case "environment-theme-background": {
859 // Published themes go to every client, so any client may read their backgrounds.
860 claims = {
861 version: 1,
862 kind: "environment-theme-background",
863 themeId: input.resource.themeId,
864 expiresAt,
865 };
866 fileName = `${input.resource.themeId}-background`;
867 break;
868 }
869 case "native-app-icon": {
870 claims = {
871 version: 1,
872 kind: "native-app-icon",
873 app: input.resource.app,
874 expiresAt,
875 };
876 fileName = "native-app-icon.png";
877 break;
878 }
879 case SOURCE_CONTROL_MEDIA_ASSET: {
880 const media = sourceControlDefinitions.mediaUrl(input.resource.url);
881 if (media === null) {
882 return yield* new AssetSourceControlMediaUrlValidationError({});
883 }
884 const { _tag, ...resource } = input.resource;
885 claims = {
886 version: 1,
887 kind: SOURCE_CONTROL_MEDIA_ASSET,
888 ...resource,
889 url: media.fetchUrl,
890 expiresAt,
891 };
892 fileName = media.fileName;
893 break;
894 }
895 }
896
897 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
898 const issuedAt = yield* Clock.currentTimeMillis;
899 expiresAt =
900 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
901 PROJECT_FAVICON_TOKEN_BUCKET_MS;
902 claims = { ...claims, expiresAt };
903 }
904 if (claims.kind === "attachment" && claims.mimeType === "text/html") {
905 // Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
906 expiresAt =
907 Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
908 claims = { ...claims, expiresAt };
909 }
910 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
911 const signer = yield* AssetSigner.AssetSigner;
912 const signature = yield* signer
913 .sign(encodedPayload)
914 .pipe(
915 Effect.mapError((cause) => new AssetSigningKeyLoadError({ resource: input.resource, cause })),
916 );
917 const token = `${encodedPayload}.${signature}`;
918 return {
919 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
920 expiresAt,
921 ...(sourcePath !== undefined ? { sourcePath } : {}),
922 ...(imageDimensions !== null ? { imageDimensions } : {}),
923 ...(fileRevision !== undefined ? { fileRevision } : {}),
924 };
925});
926
927export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
928 token: string,
929 relativePath: string,
930) {
931 const [encodedPayload, signature] = token.split(".");
932 if (!encodedPayload || !signature) return null;
933
934 const signer = yield* AssetSigner.AssetSigner;
935 const verified = yield* signer.verify(encodedPayload, signature).pipe(
936 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
937 Effect.orElseSucceed(() => false),
938 );
939 if (!verified) return null;
940
941 const claims = decodeClaims(encodedPayload);
942 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
943
944 if (claims.kind === "attachment") {
945 const config = yield* ServerConfig.ServerConfig;
946 const attachmentPath = resolveAttachmentPathById({
947 attachmentsDir: config.attachmentsDir,
948 attachmentId: claims.attachmentId,
949 });
950 if (!attachmentPath) return null;
951 const fileSystem = yield* FileSystem.FileSystem;
952 const info = yield* ProjectFaviconResolver.optionOnNotFound(
953 fileSystem.stat(attachmentPath),
954 ).pipe(
955 Effect.tapError((cause) =>
956 Effect.logError("Failed to inspect attachment asset.", {
957 attachmentId: claims.attachmentId,
958 path: attachmentPath,
959 cause,
960 }),
961 ),
962 Effect.orElseSucceed(() => Option.none()),
963 );
964 return Option.isSome(info) && info.value.type === "File"
965 ? ({
966 kind: "file",
967 path: attachmentPath,
968 ...(claims.download ? { download: true } : {}),
969 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
970 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
971 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
972 } satisfies ResolvedAsset)
973 : null;
974 }
975
976 if (claims.kind === "project-favicon") {
977 if (claims.relativePath === null) return null;
978 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
979 workspaceRoot: claims.workspaceRoot,
980 relativePath: claims.relativePath,
981 });
982 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
983 }
984
985 if (claims.kind === "project-favicon-external") {
986 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
987 Effect.tapError((cause) =>
988 Effect.logError("Failed to resolve canonical asset path.", {
989 filePath: claims.filePath,
990 cause,
991 }),
992 ),
993 Effect.orElseSucceed(() => null),
994 );
995 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
996 }
997
998 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
999 const { version: _version, ...media } = claims;
1000 return { ...media, kind: "source-control-media" } satisfies ResolvedAsset;
1001 }
1002
1003 if (claims.kind === "tool-output-image") {
1004 const image = yield* readToolOutputImage(claims).pipe(
1005 Effect.tapError((cause) =>
1006 Effect.logError("Failed to read tool output image.", {
1007 threadId: claims.threadId,
1008 itemId: claims.itemId,
1009 cause,
1010 }),
1011 ),
1012 Effect.orElseSucceed(() => null),
1013 );
1014 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
1015 }
1016
1017 if (claims.kind === "environment-theme-background") {
1018 const config = yield* ServerConfig.ServerConfig;
1019 const fileSystem = yield* FileSystem.FileSystem;
1020 // The themes directory may be a symlink; openMediaFile refuses any path that is not canonical.
1021 const themesDir = yield* fileSystem
1022 .realPath(config.environmentThemesDir)
1023 .pipe(Effect.orElseSucceed(() => null));
1024 const background = themesDir === null ? null : findThemeBackground(themesDir, claims.themeId);
1025 if (background === null) return null;
1026 const file = yield* openMediaFile(background.path).pipe(
1027 Effect.tapError((cause) =>
1028 Effect.logError("Failed to open theme background.", { path: background.path, cause }),
1029 ),
1030 Effect.orElseSucceed(() => null),
1031 );
1032 return file ? ({ kind: "file", path: background.path, file } satisfies ResolvedAsset) : null;
1033 }
1034
1035 if (claims.kind === "native-app-icon") {
1036 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
1037 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
1038 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
1039 }
1040
1041 const decodedPath = decodeRelativePath(relativePath);
1042 if (decodedPath === null) return null;
1043 const path = yield* Path.Path;
1044 if (claims.kind === "media-file-exact") {
1045 if (decodedPath !== path.basename(claims.filePath)) return null;
1046 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
1047 Effect.tapError((cause) =>
1048 Effect.logError("Failed to resolve canonical media path.", {
1049 filePath: claims.filePath,
1050 cause,
1051 }),
1052 ),
1053 Effect.orElseSucceed(() => null),
1054 );
1055 if (canonicalFile !== claims.filePath) return null;
1056 const mimeType = claims.download
1057 ? "application/octet-stream"
1058 : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
1059 if (!mimeType) return null;
1060 const file = yield* openMediaFile(canonicalFile, claims).pipe(
1061 Effect.tapError((cause) =>
1062 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
1063 ),
1064 Effect.orElseSucceed(() => null),
1065 );
1066 return file
1067 ? ({
1068 kind: "file",
1069 path: canonicalFile,
1070 mimeType,
1071 file,
1072 ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
1073 } satisfies ResolvedAsset)
1074 : null;
1075 }
1076 if (claims.kind === "workspace-file-exact") {
1077 if (decodedPath !== path.basename(claims.relativePath)) return null;
1078 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1079 workspaceRoot: claims.workspaceRoot,
1080 relativePath: claims.relativePath,
1081 });
1082 return exactWorkspaceFile
1083 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
1084 : null;
1085 }
1086 if (!isPreviewDependencyPath(decodedPath, path)) return null;
1087 const joinedRelativePath =
1088 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1089 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1090 workspaceRoot: claims.workspaceRoot,
1091 relativePath: joinedRelativePath,
1092 previewDependency: true,
1093 });
1094 return workspaceFile
1095 ? ({ kind: "file", path: workspaceFile, renderIntent: "file-preview" } satisfies ResolvedAsset)
1096 : null;
1097});