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