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