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