Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 AssetGitHubMediaUrlValidationError,
5 AssetPreviewTypeValidationError,
6 AssetProjectFaviconInspectionError,
7 AssetProjectFaviconNotFoundError,
8 AssetProjectFaviconResolutionError,
9 AssetSigningKeyLoadError,
10 AssetWorkspaceAssetInspectionError,
11 AssetWorkspaceAssetNotFoundError,
12 AssetWorkspaceContextNotFoundError,
13 AssetWorkspacePathValidationError,
14 AssetWorkspaceResolutionError,
15 AssetWorkspaceRootNormalizationError,
16 ThreadId,
17 ToolActivityNativeAppReference,
18 TurnItemId,
19} from "@t3tools/contracts";
20import {
21 audioMimeTypeFromExtension,
22 hostPreviewMimeTypeFromExtension,
23 isWorkspaceImagePreviewPath,
24 isWorkspacePreviewEntryPath,
25 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
26 WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
27} from "@t3tools/shared/filePreview";
28import {
29 IMAGE_DIMENSIONS_HEADER_BYTES,
30 readImageDimensions,
31 type ImageDimensions,
32} from "@t3tools/shared/imageDimensions";
33import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";
34import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
35import {
36 isProjectFaviconPath,
37 PROJECT_FAVICON_FALLBACK_MARKER,
38} from "@t3tools/shared/projectFavicon";
39import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
40import * as Clock from "effect/Clock";
41import * as Crypto from "effect/Crypto";
42import * as Effect from "effect/Effect";
43import * as Hex from "effect/encoding/Hex";
44import * as FileSystem from "effect/FileSystem";
45import * as Option from "effect/Option";
46import * as Path from "effect/Path";
47import * as PlatformError from "effect/PlatformError";
48import * as Schema from "effect/Schema";
49import * as Stream from "effect/Stream";
50
51import {
52 base64UrlDecodeUtf8,
53 base64UrlEncode,
54 signPayload,
55 timingSafeEqualBase64Url,
56} from "../auth/utils.ts";
57import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
58import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
59import * as ServerConfig from "../config.ts";
60import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
61import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
62import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
63import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
64import * as NativeAppIconResolver from "./NativeAppIconResolver.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 SIGNING_SECRET_NAME = "asset-access-signing-key";
72const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
73const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
74const PROJECT_FAVICON_VERSION_PREFIX = "v";
75// Clients draw project icons from a 96px thumbnail at most.
76const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
77const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
78// Extensions a document viewer or audio player may request inline. The extension comes from
79// the attachment id the server assigned, never from the client's mime type.
80const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
81 pdf: "application/pdf",
82 html: "text/html",
83 htm: "text/html",
84};
85const inlinePreviewMimeTypeForExtension = (extension: string) =>
86 INLINE_PREVIEW_MIME_TYPES[extension] ?? audioMimeTypeFromExtension(`.${extension}`) ?? undefined;
87const PREVIEW_ASSET_EXTENSIONS = new Set([
88 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
89 ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
90 ".css",
91 ".js",
92 ".mjs",
93 ".otf",
94 ".ttf",
95 ".woff",
96 ".woff2",
97]);
98
99const AssetClaimsSchema = Schema.Union([
100 Schema.Struct({
101 version: Schema.Literal(1),
102 kind: Schema.Literal("workspace-file"),
103 workspaceRoot: Schema.String,
104 baseRelativePath: Schema.String,
105 expiresAt: Schema.Number,
106 }),
107 Schema.Struct({
108 version: Schema.Literal(1),
109 kind: Schema.Literal("workspace-file-exact"),
110 workspaceRoot: Schema.String,
111 relativePath: Schema.String,
112 expiresAt: Schema.Number,
113 }),
114 Schema.Struct({
115 version: Schema.Literal(1),
116 kind: Schema.Literal("media-file-exact"),
117 filePath: Schema.String,
118 device: Schema.String,
119 inode: Schema.String,
120 expiresAt: Schema.Number,
121 }),
122 Schema.Struct({
123 version: Schema.Literal(1),
124 kind: Schema.Literal("attachment"),
125 attachmentId: Schema.String,
126 /** Decided at mint time. Absent tokens (from before this field) serve
127 inline, which is only ever the image case. */
128 download: Schema.optionalKey(Schema.Boolean),
129 /** Display name and mime the caller supplied at mint time; drive the
130 download filename and Content-Type. */
131 fileName: Schema.optionalKey(Schema.String),
132 mimeType: Schema.optionalKey(Schema.String),
133 renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
134 expiresAt: Schema.Number,
135 }),
136 Schema.Struct({
137 version: Schema.Literal(1),
138 kind: Schema.Literal("project-favicon"),
139 workspaceRoot: Schema.String,
140 relativePath: Schema.NullOr(Schema.String),
141 expiresAt: Schema.Number,
142 }),
143 Schema.Struct({
144 version: Schema.Literal(1),
145 kind: Schema.Literal("project-favicon-external"),
146 filePath: Schema.String,
147 expiresAt: Schema.Number,
148 }),
149 Schema.Struct({
150 version: Schema.Literal(1),
151 kind: Schema.Literal("native-app-icon"),
152 app: ToolActivityNativeAppReference,
153 expiresAt: Schema.Number,
154 }),
155 Schema.Struct({
156 version: Schema.Literal(1),
157 kind: Schema.Literal("tool-output-image"),
158 threadId: ThreadId,
159 itemId: TurnItemId,
160 index: Schema.Number,
161 expiresAt: Schema.Number,
162 }),
163 Schema.Struct({
164 version: Schema.Literal(1),
165 kind: Schema.Literal("github-media"),
166 /** Already narrowed to a GitHub media host at mint time; the signature is what keeps it there. */
167 url: Schema.String,
168 cwd: Schema.String,
169 expiresAt: Schema.Number,
170 }),
171]);
172type AssetClaims = typeof AssetClaimsSchema.Type;
173
174const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
175const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
176const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
177
178export type ResolvedAsset =
179 | {
180 readonly kind: "file";
181 readonly path: string;
182 readonly download?: boolean;
183 readonly fileName?: string;
184 readonly mimeType?: string;
185 readonly file?: OpenMediaFile;
186 readonly renderIntent?: "mcp-app";
187 }
188 | {
189 readonly kind: "bytes";
190 readonly bytes: Uint8Array;
191 readonly mimeType: string;
192 }
193 | {
194 readonly kind: "github-media";
195 readonly url: string;
196 readonly cwd: string;
197 /** When the signed URL that granted this stops working, which bounds how long a client
198 may keep the bytes it fetched with it. */
199 readonly expiresAt: number;
200 };
201
202function decodeClaims(encodedPayload: string): AssetClaims | null {
203 try {
204 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
205 } catch {
206 return null;
207 }
208}
209
210function decodeRelativePath(value: string): string | null {
211 try {
212 return decodeURIComponent(value);
213 } catch {
214 return null;
215 }
216}
217
218const optionOnNotFound = <A, R>(
219 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
220): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
221 effect.pipe(
222 Effect.asSome,
223 Effect.catchTags({
224 PlatformError: (error) =>
225 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
226 }),
227 );
228
229/** Reads a stored MCP HTML snapshot; null means it exceeds the preview limit. */
230export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
231 const fileSystem = yield* FileSystem.FileSystem;
232 // Stored snapshots also contain a bounded CSP meta tag (up to 32 domains
233 // per directive). Bound the read even if the attachment grows after minting.
234 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
235 const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
236 const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
237 if (size > limit) return null;
238 const bytes = new Uint8Array(size);
239 let position = 0;
240 for (const chunk of chunks) {
241 bytes.set(chunk, position);
242 position += chunk.byteLength;
243 }
244 return bytes;
245});
246
247/**
248 * Decodes one image a tool returned inline; null when the stored item has no
249 * such image, or it is larger than a provider turn accepts.
250 */
251const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
252 readonly threadId: ThreadId;
253 readonly itemId: TurnItemId;
254 readonly index: number;
255}) {
256 const orchestrator = yield* Orchestrator.OrchestratorV2;
257 const item = yield* orchestrator.getTurnItem(input);
258 const image =
259 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
260 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
261 ? null
262 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
263});
264
265/** Serves an `.icns` favicon as its embedded PNG, since browsers cannot draw it. */
266const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* (
267 filePath: string,
268) {
269 if (!filePath.toLowerCase().endsWith(".icns")) {
270 return { kind: "file", path: filePath } satisfies ResolvedAsset;
271 }
272 const fileSystem = yield* FileSystem.FileSystem;
273 const bytes = yield* fileSystem.readFile(filePath).pipe(
274 Effect.tapError((cause) =>
275 Effect.logError("Failed to read project icon image.", { filePath, cause }),
276 ),
277 Effect.orElseSucceed(() => null),
278 );
279 const png = bytes ? extractIcnsPng(bytes, PROJECT_FAVICON_ICNS_MIN_SIZE) : null;
280 return png
281 ? ({ kind: "bytes", bytes: png, mimeType: "image/png" } satisfies ResolvedAsset)
282 : null;
283});
284
285const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
286 filePath: string,
287) {
288 const fileSystem = yield* FileSystem.FileSystem;
289 const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
290 if (Option.isNone(canonicalFile)) return null;
291
292 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
293 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
294});
295
296const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
297 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
298 const fileSystem = yield* FileSystem.FileSystem;
299 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
300 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
301 Effect.asSome,
302 Effect.catchTags({
303 WorkspacePathOutsideRootError: () => Effect.succeedNone,
304 }),
305 );
306 if (Option.isNone(resolved)) return null;
307
308 const [canonicalRoot, canonicalFile] = yield* Effect.all([
309 optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
310 optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
311 ]);
312 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
313
314 const path = yield* Path.Path;
315 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
316 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
317
318 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
319 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
320 },
321);
322
323const resolveCanonicalWorkspaceFileForRequest = (input: {
324 readonly workspaceRoot: string;
325 readonly relativePath: string;
326}) =>
327 resolveCanonicalWorkspaceFile(input).pipe(
328 Effect.tapError((cause) =>
329 Effect.logError("Failed to resolve canonical asset path.", {
330 workspaceRoot: input.workspaceRoot,
331 relativePath: input.relativePath,
332 cause,
333 }),
334 ),
335 Effect.orElseSucceed(() => null),
336 );
337
338/**
339 * Reads pixel dimensions from an image's header so clients can reserve the
340 * exact box before the bytes arrive. Best effort: an unreadable or unsupported
341 * file just leaves the field out, and the client measures after decode. Only
342 * formats the parser understands are opened; SVG and the rest are skipped.
343 */
344const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
345
346/** From the identity-checked, non-blocking handle the caller already holds. */
347const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
348 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
349 Effect.map(readImageDimensions),
350 Effect.orElseSucceed((): ImageDimensions | null => null),
351 );
352
353/**
354 * Opens through `openMediaFile` so a path swapped for a FIFO cannot block the
355 * request; a regular open would wait for a writer that never comes.
356 */
357const readImageDimensionsFromHeader = (filePath: string) =>
358 openMediaFile(filePath).pipe(
359 Effect.flatMap((file) =>
360 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
361 ),
362 Effect.scoped,
363 Effect.orElseSucceed((): ImageDimensions | null => null),
364 );
365
366const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
367 function* (input: {
368 readonly requestedPath: string;
369 readonly resource: AssetResource;
370 readonly expiresAt: number;
371 }) {
372 const path = yield* Path.Path;
373 const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe(
374 Effect.mapError(
375 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
376 ),
377 );
378 if (!canonicalFile) {
379 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
380 }
381 if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
382 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
383 }
384 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
385 const opened = yield* openMediaFile(canonicalFile).pipe(
386 Effect.flatMap((file) =>
387 file === null
388 ? Effect.succeed(null)
389 : Effect.map(
390 wantsDimensions
391 ? readImageDimensionsFromOpenFile(canonicalFile, file)
392 : Effect.succeed(null),
393 (dimensions) => ({
394 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
395 dimensions,
396 }),
397 ),
398 ),
399 Effect.scoped,
400 Effect.mapError(
401 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
402 ),
403 );
404 if (!opened) {
405 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
406 }
407 return {
408 claims: {
409 version: 1 as const,
410 kind: "media-file-exact" as const,
411 filePath: canonicalFile,
412 ...opened.identity,
413 expiresAt: input.expiresAt,
414 },
415 fileName: path.basename(canonicalFile),
416 imageDimensions: opened.dimensions,
417 };
418 },
419);
420
421const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
422 function* (input: {
423 readonly workspaceRoot: string;
424 readonly requestedPath: string;
425 readonly resource: AssetResource;
426 readonly expiresAt: number;
427 }) {
428 const path = yield* Path.Path;
429 const fileSystem = yield* FileSystem.FileSystem;
430 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
431 const relativePath = path.isAbsolute(input.requestedPath)
432 ? path.relative(input.workspaceRoot, input.requestedPath)
433 : input.requestedPath;
434 const resolved = yield* workspacePaths
435 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
436 .pipe(
437 Effect.mapError(
438 (cause) =>
439 new AssetWorkspacePathValidationError({
440 resource: input.resource,
441 cause,
442 }),
443 ),
444 );
445 if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
446 return yield* new AssetPreviewTypeValidationError({
447 resource: input.resource,
448 });
449 }
450 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
451 workspaceRoot: input.workspaceRoot,
452 relativePath: resolved.relativePath,
453 }).pipe(
454 Effect.mapError(
455 (cause) =>
456 new AssetWorkspaceAssetInspectionError({
457 resource: input.resource,
458 cause,
459 }),
460 ),
461 );
462 if (!canonicalFile) {
463 return yield* new AssetWorkspaceAssetNotFoundError({
464 resource: input.resource,
465 });
466 }
467 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
468 Effect.mapError(
469 (cause) =>
470 new AssetWorkspaceResolutionError({
471 resource: input.resource,
472 cause,
473 }),
474 ),
475 );
476 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
477 path.extname(resolved.relativePath).toLowerCase(),
478 )
479 ? yield* readImageDimensionsFromHeader(canonicalFile)
480 : null;
481 return {
482 claims: isWorkspaceImagePreviewPath(resolved.relativePath)
483 ? {
484 version: 1 as const,
485 kind: "workspace-file-exact" as const,
486 workspaceRoot: canonicalWorkspaceRoot,
487 relativePath: resolved.relativePath,
488 expiresAt: input.expiresAt,
489 }
490 : {
491 version: 1 as const,
492 kind: "workspace-file" as const,
493 workspaceRoot: canonicalWorkspaceRoot,
494 baseRelativePath: path.dirname(resolved.relativePath),
495 expiresAt: input.expiresAt,
496 },
497 fileName: path.basename(resolved.relativePath),
498 imageDimensions,
499 };
500 },
501);
502
503export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
504 readonly resource: AssetResource;
505 readonly workspaceRoot?: string;
506 readonly projectFaviconPath?: string;
507 /** The project's clone has not landed, so its icon is reported missing without a lookup. */
508 readonly projectCheckoutPending?: boolean;
509}) {
510 const fileSystem = yield* FileSystem.FileSystem;
511 const path = yield* Path.Path;
512 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
513 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
514 let claims: AssetClaims;
515 let fileName: string;
516 let sourcePath: string | undefined;
517 let imageDimensions: ImageDimensions | null = null;
518
519 switch (input.resource._tag) {
520 case "media-file": {
521 let requestedPath = expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory);
522 if (!path.isAbsolute(requestedPath)) {
523 if (!input.workspaceRoot) {
524 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
525 }
526 const workspaceRoot = yield* workspacePaths
527 .normalizeWorkspaceRoot(input.workspaceRoot)
528 .pipe(
529 Effect.mapError(
530 (cause) =>
531 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
532 ),
533 );
534 requestedPath = path.resolve(workspaceRoot, requestedPath);
535 }
536 const finalized = yield* finalizeAbsoluteMediaFileAsset({
537 requestedPath,
538 resource: input.resource,
539 expiresAt,
540 });
541 claims = finalized.claims;
542 fileName = finalized.fileName;
543 imageDimensions = finalized.imageDimensions;
544 break;
545 }
546 case "workspace-file": {
547 if (!input.workspaceRoot) {
548 return yield* new AssetWorkspaceContextNotFoundError({
549 resource: input.resource,
550 });
551 }
552 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
553 Effect.mapError(
554 (cause) =>
555 new AssetWorkspaceRootNormalizationError({
556 resource: input.resource,
557 cause,
558 }),
559 ),
560 );
561 const finalized = yield* finalizeWorkspaceFileAsset({
562 workspaceRoot,
563 requestedPath: input.resource.path,
564 resource: input.resource,
565 expiresAt,
566 });
567 claims = finalized.claims;
568 fileName = finalized.fileName;
569 imageDimensions = finalized.imageDimensions;
570 break;
571 }
572 case "draft-workspace-file": {
573 // The draft names its workspace root in the resource itself; an explicit
574 // root only overrides it.
575 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
576 if (path.isAbsolute(input.resource.path)) {
577 // An absolute draft path serves exactly like an absolute media path.
578 const finalized = yield* finalizeAbsoluteMediaFileAsset({
579 requestedPath: input.resource.path,
580 resource: input.resource,
581 expiresAt,
582 });
583 claims = finalized.claims;
584 fileName = finalized.fileName;
585 imageDimensions = finalized.imageDimensions;
586 break;
587 }
588 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
589 Effect.mapError(
590 (cause) =>
591 new AssetWorkspaceRootNormalizationError({
592 resource: input.resource,
593 cause,
594 }),
595 ),
596 );
597 const finalized = yield* finalizeWorkspaceFileAsset({
598 workspaceRoot,
599 requestedPath: input.resource.path,
600 resource: input.resource,
601 expiresAt,
602 });
603 claims = finalized.claims;
604 fileName = finalized.fileName;
605 imageDimensions = finalized.imageDimensions;
606 break;
607 }
608 case "attachment": {
609 const config = yield* ServerConfig.ServerConfig;
610 const attachmentPath = resolveAttachmentPathById({
611 attachmentsDir: config.attachmentsDir,
612 attachmentId: input.resource.attachmentId,
613 });
614 if (!attachmentPath) {
615 return yield* new AssetAttachmentNotFoundError({
616 resource: input.resource,
617 });
618 }
619 // Generic files carry their extension inside the attachment id (that
620 // shape resolves the on-disk path); images do not. Videos and images
621 // render inline. Other generic files download unless a viewer requests
622 // a supported document or audio format inline.
623 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
624 const isGenericFile = extension !== null;
625 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
626 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
627 const inlinePreviewMimeType =
628 input.resource.disposition === "inline" && extension !== null
629 ? inlinePreviewMimeTypeForExtension(extension)
630 : undefined;
631 if (!isGenericFile) {
632 imageDimensions = yield* readImageDimensionsFromHeader(attachmentPath);
633 }
634 claims = {
635 version: 1,
636 kind: "attachment",
637 attachmentId: input.resource.attachmentId,
638 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
639 ? { download: true }
640 : {}),
641 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
642 ...(inlinePreviewMimeType !== undefined
643 ? { mimeType: inlinePreviewMimeType }
644 : input.resource.mimeType !== undefined
645 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
646 : {}),
647 ...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
648 ? { renderIntent: "mcp-app" as const }
649 : {}),
650 expiresAt,
651 };
652 fileName = input.resource.fileName ?? path.basename(attachmentPath);
653 break;
654 }
655 case "project-favicon": {
656 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
657 Effect.mapError(
658 (cause) =>
659 new AssetWorkspaceRootNormalizationError({
660 resource: input.resource,
661 cause,
662 }),
663 ),
664 );
665 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
666 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
667 const faviconPath = input.projectCheckoutPending
668 ? null
669 : yield* faviconResolver
670 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
671 .pipe(
672 Effect.mapError(
673 (cause) =>
674 new AssetProjectFaviconResolutionError({
675 resource: input.resource,
676 cause,
677 }),
678 ),
679 );
680 const isExternalOverride =
681 faviconPath !== null &&
682 input.projectFaviconPath !== undefined &&
683 path.isAbsolute(input.projectFaviconPath) &&
684 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
685 const relativePath =
686 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
687 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
688 if (sourceFaviconPath && !isProjectFaviconPath(sourceFaviconPath)) {
689 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
690 }
691 sourcePath = sourceFaviconPath ?? undefined;
692 const canonicalFaviconPath = sourceFaviconPath
693 ? yield* (
694 isExternalOverride
695 ? resolveCanonicalFile(sourceFaviconPath)
696 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
697 ).pipe(
698 Effect.mapError(
699 (cause) =>
700 new AssetProjectFaviconInspectionError({
701 resource: input.resource,
702 cause,
703 }),
704 ),
705 )
706 : null;
707 if (sourceFaviconPath && !canonicalFaviconPath) {
708 return yield* new AssetProjectFaviconNotFoundError({
709 resource: input.resource,
710 });
711 }
712 claims =
713 isExternalOverride && canonicalFaviconPath
714 ? {
715 version: 1,
716 kind: "project-favicon-external",
717 filePath: canonicalFaviconPath,
718 expiresAt,
719 }
720 : {
721 version: 1,
722 kind: "project-favicon",
723 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
724 Effect.mapError(
725 (cause) =>
726 new AssetWorkspaceResolutionError({
727 resource: input.resource,
728 cause,
729 }),
730 ),
731 ),
732 relativePath,
733 expiresAt,
734 };
735 if (sourceFaviconPath && canonicalFaviconPath) {
736 const crypto = yield* Crypto.Crypto;
737 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
738 Effect.mapError(
739 (cause) =>
740 new AssetProjectFaviconInspectionError({
741 resource: input.resource,
742 cause,
743 }),
744 ),
745 );
746 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
747 Effect.map(Hex.encode),
748 Effect.mapError(
749 (cause) =>
750 new AssetProjectFaviconInspectionError({
751 resource: input.resource,
752 cause,
753 }),
754 ),
755 );
756 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
757 } else {
758 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
759 }
760 break;
761 }
762 case "tool-output-image": {
763 const image = yield* readToolOutputImage(input.resource).pipe(
764 Effect.mapError(
765 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
766 ),
767 );
768 if (image === null) {
769 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
770 }
771 claims = {
772 version: 1,
773 kind: "tool-output-image",
774 threadId: input.resource.threadId,
775 itemId: input.resource.itemId,
776 index: input.resource.index,
777 expiresAt,
778 };
779 // The allowed types are all `image/<extension>`.
780 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
781 imageDimensions = readImageDimensions(image.bytes);
782 break;
783 }
784 case "native-app-icon": {
785 claims = {
786 version: 1,
787 kind: "native-app-icon",
788 app: input.resource.app,
789 expiresAt,
790 };
791 fileName = "native-app-icon.png";
792 break;
793 }
794 case "github-media": {
795 const fetchUrl = githubMediaFetchUrl(input.resource.url);
796 if (fetchUrl === null) {
797 return yield* new AssetGitHubMediaUrlValidationError({});
798 }
799 claims = {
800 version: 1,
801 kind: "github-media",
802 url: fetchUrl,
803 cwd: input.resource.cwd,
804 expiresAt,
805 };
806 fileName = githubMediaFileName(fetchUrl);
807 break;
808 }
809 }
810
811 const secretStore = yield* ServerSecretStore.ServerSecretStore;
812 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
813 Effect.mapError(
814 (cause) =>
815 new AssetSigningKeyLoadError({
816 resource: input.resource,
817 cause,
818 }),
819 ),
820 );
821 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
822 const issuedAt = yield* Clock.currentTimeMillis;
823 expiresAt =
824 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
825 PROJECT_FAVICON_TOKEN_BUCKET_MS;
826 claims = { ...claims, expiresAt };
827 }
828 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
829 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
830 return {
831 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
832 expiresAt,
833 ...(sourcePath !== undefined ? { sourcePath } : {}),
834 ...(imageDimensions !== null ? { imageDimensions } : {}),
835 };
836});
837
838export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
839 token: string,
840 relativePath: string,
841) {
842 const [encodedPayload, signature] = token.split(".");
843 if (!encodedPayload || !signature) return null;
844
845 const secretStore = yield* ServerSecretStore.ServerSecretStore;
846 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
847 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
848 Effect.orElseSucceed(() => null),
849 );
850 if (!signingSecret) return null;
851 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
852
853 const claims = decodeClaims(encodedPayload);
854 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
855
856 if (claims.kind === "attachment") {
857 const config = yield* ServerConfig.ServerConfig;
858 const attachmentPath = resolveAttachmentPathById({
859 attachmentsDir: config.attachmentsDir,
860 attachmentId: claims.attachmentId,
861 });
862 if (!attachmentPath) return null;
863 const fileSystem = yield* FileSystem.FileSystem;
864 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
865 Effect.tapError((cause) =>
866 Effect.logError("Failed to inspect attachment asset.", {
867 attachmentId: claims.attachmentId,
868 path: attachmentPath,
869 cause,
870 }),
871 ),
872 Effect.orElseSucceed(() => Option.none()),
873 );
874 return Option.isSome(info) && info.value.type === "File"
875 ? ({
876 kind: "file",
877 path: attachmentPath,
878 ...(claims.download ? { download: true } : {}),
879 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
880 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
881 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
882 } satisfies ResolvedAsset)
883 : null;
884 }
885
886 if (claims.kind === "project-favicon") {
887 if (claims.relativePath === null) return null;
888 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
889 workspaceRoot: claims.workspaceRoot,
890 relativePath: claims.relativePath,
891 });
892 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
893 }
894
895 if (claims.kind === "project-favicon-external") {
896 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
897 Effect.tapError((cause) =>
898 Effect.logError("Failed to resolve canonical asset path.", {
899 filePath: claims.filePath,
900 cause,
901 }),
902 ),
903 Effect.orElseSucceed(() => null),
904 );
905 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
906 }
907
908 if (claims.kind === "github-media") {
909 return {
910 kind: "github-media",
911 url: claims.url,
912 cwd: claims.cwd,
913 expiresAt: claims.expiresAt,
914 } satisfies ResolvedAsset;
915 }
916
917 if (claims.kind === "tool-output-image") {
918 const image = yield* readToolOutputImage(claims).pipe(
919 Effect.tapError((cause) =>
920 Effect.logError("Failed to read tool output image.", {
921 threadId: claims.threadId,
922 itemId: claims.itemId,
923 cause,
924 }),
925 ),
926 Effect.orElseSucceed(() => null),
927 );
928 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
929 }
930
931 if (claims.kind === "native-app-icon") {
932 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
933 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
934 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
935 }
936
937 const decodedPath = decodeRelativePath(relativePath);
938 if (decodedPath === null) return null;
939 const path = yield* Path.Path;
940 if (claims.kind === "media-file-exact") {
941 if (decodedPath !== path.basename(claims.filePath)) return null;
942 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
943 Effect.tapError((cause) =>
944 Effect.logError("Failed to resolve canonical media path.", {
945 filePath: claims.filePath,
946 cause,
947 }),
948 ),
949 Effect.orElseSucceed(() => null),
950 );
951 if (canonicalFile !== claims.filePath) return null;
952 const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
953 if (!mimeType) return null;
954 const file = yield* openMediaFile(canonicalFile, claims).pipe(
955 Effect.tapError((cause) =>
956 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
957 ),
958 Effect.orElseSucceed(() => null),
959 );
960 return file
961 ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
962 : null;
963 }
964 if (claims.kind === "workspace-file-exact") {
965 if (decodedPath !== path.basename(claims.relativePath)) return null;
966 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
967 workspaceRoot: claims.workspaceRoot,
968 relativePath: claims.relativePath,
969 });
970 return exactWorkspaceFile
971 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
972 : null;
973 }
974 const segments = decodedPath.split(/[\\/]/);
975 if (
976 decodedPath.length === 0 ||
977 decodedPath.includes("\0") ||
978 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
979 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
980 ) {
981 return null;
982 }
983 const joinedRelativePath =
984 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
985 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
986 workspaceRoot: claims.workspaceRoot,
987 relativePath: joinedRelativePath,
988 });
989 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
990});