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

AssetAccess.ts

999 lines36.0 KB

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