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 {
51 base64UrlDecodeUtf8,
52 base64UrlEncode,
53 signPayload,
54 timingSafeEqualBase64Url,
55} from "../auth/utils.ts";
56import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
57import { makeIsServerInternalPath } from "../auth/serverInternalPaths.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
225export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
226 const fileSystem = yield* FileSystem.FileSystem;
227 // Allow space for stored CSP tags, but bound reads if the attachment grows after minting.
228 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
229 const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
230 const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
231 if (size > limit) return null;
232 const bytes = new Uint8Array(size);
233 let position = 0;
234 for (const chunk of chunks) {
235 bytes.set(chunk, position);
236 position += chunk.byteLength;
237 }
238 return bytes;
239});
240
241const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
242 readonly threadId: ThreadId;
243 readonly itemId: TurnItemId;
244 readonly index: number;
245}) {
246 const orchestrator = yield* Orchestrator.OrchestratorV2;
247 const item = yield* orchestrator.getTurnItem(input);
248 const image =
249 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
250 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
251 ? null
252 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
253});
254
255// Browsers cannot draw .icns; serve its embedded PNG.
256const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* (
257 filePath: string,
258) {
259 if (!filePath.toLowerCase().endsWith(".icns")) {
260 return { kind: "file", path: filePath } satisfies ResolvedAsset;
261 }
262 const fileSystem = yield* FileSystem.FileSystem;
263 const bytes = yield* fileSystem.readFile(filePath).pipe(
264 Effect.tapError((cause) =>
265 Effect.logError("Failed to read project icon image.", { filePath, cause }),
266 ),
267 Effect.orElseSucceed(() => null),
268 );
269 const png = bytes ? extractIcnsPng(bytes, PROJECT_FAVICON_ICNS_MIN_SIZE) : null;
270 return png
271 ? ({ kind: "bytes", bytes: png, mimeType: "image/png" } satisfies ResolvedAsset)
272 : null;
273});
274
275const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
276 filePath: string,
277) {
278 const fileSystem = yield* FileSystem.FileSystem;
279 const canonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
280 fileSystem.realPath(filePath),
281 );
282 if (Option.isNone(canonicalFile)) return null;
283
284 const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
285 if (Option.isNone(info) || info.value.type !== "File") return null;
286 const isServerInternalPath = yield* makeIsServerInternalPath;
287 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
288});
289
290const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
291 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
292 const fileSystem = yield* FileSystem.FileSystem;
293 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
294 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
295 Effect.asSome,
296 Effect.catchTags({
297 WorkspacePathOutsideRootError: () => Effect.succeedNone,
298 }),
299 );
300 if (Option.isNone(resolved)) return null;
301
302 const [canonicalRoot, canonicalFile] = yield* Effect.all([
303 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
304 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
305 ]);
306 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
307
308 const path = yield* Path.Path;
309 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
310 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
311
312 const info = yield* ProjectFaviconResolver.optionOnNotFound(
313 fileSystem.stat(canonicalFile.value),
314 );
315 if (Option.isNone(info) || info.value.type !== "File") return null;
316 const isServerInternalPath = yield* makeIsServerInternalPath;
317 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
318 },
319);
320
321const resolveCanonicalWorkspaceFileForRequest = (input: {
322 readonly workspaceRoot: string;
323 readonly relativePath: string;
324}) =>
325 resolveCanonicalWorkspaceFile(input).pipe(
326 Effect.tapError((cause) =>
327 Effect.logError("Failed to resolve canonical asset path.", {
328 workspaceRoot: input.workspaceRoot,
329 relativePath: input.relativePath,
330 cause,
331 }),
332 ),
333 Effect.orElseSucceed(() => null),
334 );
335
336const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
337
338const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
339 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
340 Effect.map(readImageDimensions),
341 Effect.orElseSucceed((): ImageDimensions | null => null),
342 );
343
344// Non-blocking open prevents swapped-in FIFOs from hanging the request.
345const readImageDimensionsFromHeader = (filePath: string) =>
346 openMediaFile(filePath).pipe(
347 Effect.flatMap((file) =>
348 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
349 ),
350 Effect.scoped,
351 Effect.orElseSucceed((): ImageDimensions | null => null),
352 );
353
354const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
355 function* (input: {
356 readonly requestedPath: string;
357 readonly expectedCanonicalPath?: string;
358 readonly workspaceRoot: string | undefined;
359 readonly resource: AssetResource;
360 readonly expiresAt: number;
361 }) {
362 const path = yield* Path.Path;
363 // Resolving a network path makes Windows sign in to its host with the
364 // user's NTLM credentials, so only the thread's own project may be on a share.
365 // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
366 // the resolved path this check approved.
367 const requestedPath = path.resolve(input.requestedPath);
368 if (
369 isNetworkPath(input.requestedPath) &&
370 (input.workspaceRoot === undefined ||
371 !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
372 ) {
373 return yield* new AssetWorkspaceAssetNotFoundError({
374 resource: input.resource,
375 checkedPath: input.requestedPath,
376 });
377 }
378 const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
379 Effect.mapError(
380 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
381 ),
382 );
383 // The workspace caller pins its containment-checked path; never follow a
384 // replacement symlink to a different file during this second resolution.
385 if (
386 !canonicalFile ||
387 (input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
388 ) {
389 return yield* new AssetWorkspaceAssetNotFoundError({
390 resource: input.resource,
391 checkedPath: input.requestedPath,
392 });
393 }
394 const download =
395 input.resource._tag === "media-file" && input.resource.disposition === "attachment";
396 if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
397 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
398 }
399 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
400 const opened = yield* openMediaFile(canonicalFile).pipe(
401 Effect.flatMap((file) =>
402 file === null
403 ? Effect.succeed(null)
404 : Effect.map(
405 wantsDimensions
406 ? readImageDimensionsFromOpenFile(canonicalFile, file)
407 : Effect.succeed(null),
408 (dimensions) => ({
409 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
410 fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
411 dimensions,
412 }),
413 ),
414 ),
415 Effect.scoped,
416 Effect.mapError(
417 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
418 ),
419 );
420 if (!opened) {
421 return yield* new AssetWorkspaceAssetNotFoundError({
422 resource: input.resource,
423 checkedPath: input.requestedPath,
424 });
425 }
426 return {
427 claims: {
428 version: 1 as const,
429 kind: "media-file-exact" as const,
430 filePath: canonicalFile,
431 ...(download ? { download: true } : {}),
432 ...opened.identity,
433 expiresAt: input.expiresAt,
434 },
435 fileName: path.basename(canonicalFile),
436 fileRevision: opened.fileRevision,
437 imageDimensions: opened.dimensions,
438 };
439 },
440);
441
442const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
443 function* (input: {
444 readonly workspaceRoot: string;
445 readonly requestedPath: string;
446 readonly resource: AssetResource;
447 readonly expiresAt: number;
448 }) {
449 const path = yield* Path.Path;
450 const fileSystem = yield* FileSystem.FileSystem;
451 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
452 const relativePath = path.isAbsolute(input.requestedPath)
453 ? path.relative(input.workspaceRoot, input.requestedPath)
454 : input.requestedPath;
455 const resolved = yield* workspacePaths
456 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
457 .pipe(
458 Effect.mapError(
459 (cause) =>
460 new AssetWorkspacePathValidationError({
461 resource: input.resource,
462 cause,
463 }),
464 ),
465 );
466 const isDraftMedia =
467 input.resource._tag === "draft-workspace-file" &&
468 (isWorkspaceAudioPreviewPath(resolved.relativePath) ||
469 isWorkspaceVideoPreviewPath(resolved.relativePath));
470 if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
471 return yield* new AssetPreviewTypeValidationError({
472 resource: input.resource,
473 });
474 }
475 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
476 workspaceRoot: input.workspaceRoot,
477 relativePath: resolved.relativePath,
478 }).pipe(
479 Effect.mapError(
480 (cause) =>
481 new AssetWorkspaceAssetInspectionError({
482 resource: input.resource,
483 cause,
484 }),
485 ),
486 );
487 if (!canonicalFile) {
488 return yield* new AssetWorkspaceAssetNotFoundError({
489 resource: input.resource,
490 });
491 }
492 if (isDraftMedia) {
493 return yield* finalizeAbsoluteMediaFileAsset({
494 ...input,
495 requestedPath: canonicalFile,
496 expectedCanonicalPath: canonicalFile,
497 });
498 }
499 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
500 Effect.mapError(
501 (cause) =>
502 new AssetWorkspaceResolutionError({
503 resource: input.resource,
504 cause,
505 }),
506 ),
507 );
508 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
509 path.extname(resolved.relativePath).toLowerCase(),
510 )
511 ? yield* readImageDimensionsFromHeader(canonicalFile)
512 : null;
513 return {
514 claims: !/\.html?$/i.test(resolved.relativePath)
515 ? {
516 version: 1 as const,
517 kind: "workspace-file-exact" as const,
518 workspaceRoot: canonicalWorkspaceRoot,
519 relativePath: resolved.relativePath,
520 expiresAt: input.expiresAt,
521 }
522 : {
523 version: 1 as const,
524 kind: "workspace-file" as const,
525 workspaceRoot: canonicalWorkspaceRoot,
526 baseRelativePath: path.dirname(resolved.relativePath),
527 expiresAt: input.expiresAt,
528 },
529 fileName: path.basename(resolved.relativePath),
530 imageDimensions,
531 fileRevision: undefined,
532 };
533 },
534);
535
536export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
537 readonly resource: AssetResource;
538 readonly workspaceRoot?: string;
539 readonly projectFaviconPath?: string;
540 /** Where a cloned project's checkout stands, while the clone tracker still knows it. */
541 readonly projectCheckout?: "pending" | "cloned";
542}) {
543 const fileSystem = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
546 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
547 let claims: AssetClaims;
548 let fileName: string;
549 let sourcePath: string | undefined;
550 let imageDimensions: ImageDimensions | null = null;
551 let fileRevision: string | undefined;
552
553 switch (input.resource._tag) {
554 case "media-file": {
555 let requestedPath = expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory);
556 if (!path.isAbsolute(requestedPath)) {
557 if (!input.workspaceRoot) {
558 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
559 }
560 const workspaceRoot = yield* workspacePaths
561 .normalizeWorkspaceRoot(input.workspaceRoot)
562 .pipe(
563 Effect.mapError(
564 (cause) =>
565 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
566 ),
567 );
568 requestedPath = path.resolve(workspaceRoot, requestedPath);
569 }
570 const finalized = yield* finalizeAbsoluteMediaFileAsset({
571 requestedPath,
572 workspaceRoot: input.workspaceRoot,
573 resource: input.resource,
574 expiresAt,
575 });
576 claims = finalized.claims;
577 fileName = finalized.fileName;
578 imageDimensions = finalized.imageDimensions;
579 fileRevision = finalized.fileRevision;
580 break;
581 }
582 case "workspace-file": {
583 if (!input.workspaceRoot) {
584 return yield* new AssetWorkspaceContextNotFoundError({
585 resource: input.resource,
586 });
587 }
588 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
589 Effect.mapError(
590 (cause) =>
591 new AssetWorkspaceRootNormalizationError({
592 resource: input.resource,
593 cause,
594 }),
595 ),
596 );
597 const finalized = yield* finalizeWorkspaceFileAsset({
598 workspaceRoot,
599 requestedPath: input.resource.path,
600 resource: input.resource,
601 expiresAt,
602 });
603 claims = finalized.claims;
604 fileName = finalized.fileName;
605 imageDimensions = finalized.imageDimensions;
606 break;
607 }
608 case "draft-workspace-file": {
609 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
610 const hostPath = input.resource.path.startsWith("~/")
611 ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
612 : input.resource.path;
613 if (path.isAbsolute(hostPath)) {
614 const finalized = yield* finalizeAbsoluteMediaFileAsset({
615 requestedPath: hostPath,
616 workspaceRoot: draftWorkspaceRoot,
617 resource: input.resource,
618 expiresAt,
619 });
620 claims = finalized.claims;
621 fileName = finalized.fileName;
622 imageDimensions = finalized.imageDimensions;
623 fileRevision = finalized.fileRevision;
624 break;
625 }
626 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
627 Effect.mapError(
628 (cause) =>
629 new AssetWorkspaceRootNormalizationError({
630 resource: input.resource,
631 cause,
632 }),
633 ),
634 );
635 const finalized = yield* finalizeWorkspaceFileAsset({
636 workspaceRoot,
637 requestedPath: input.resource.path,
638 resource: input.resource,
639 expiresAt,
640 });
641 claims = finalized.claims;
642 fileName = finalized.fileName;
643 imageDimensions = finalized.imageDimensions;
644 fileRevision = finalized.fileRevision;
645 break;
646 }
647 case "attachment": {
648 const config = yield* ServerConfig.ServerConfig;
649 const attachmentPath = resolveAttachmentPathById({
650 attachmentsDir: config.attachmentsDir,
651 attachmentId: input.resource.attachmentId,
652 });
653 if (!attachmentPath) {
654 return yield* new AssetAttachmentNotFoundError({
655 resource: input.resource,
656 });
657 }
658 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
659 const isGenericFile = extension !== null;
660 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
661 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
662 const inlinePreviewMimeType =
663 input.resource.disposition === "inline" && extension !== null
664 ? inlinePreviewMimeTypeForExtension(extension)
665 : undefined;
666 if (!isGenericFile) {
667 imageDimensions = yield* fileSystem.realPath(attachmentPath).pipe(
668 Effect.flatMap(readImageDimensionsFromHeader),
669 Effect.orElseSucceed(() => null),
670 );
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 digest = yield* Digest.Digest;
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* digest.digest(Digest.sha256, 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* ProjectFaviconResolver.optionOnNotFound(
912 fileSystem.stat(attachmentPath),
913 ).pipe(
914 Effect.tapError((cause) =>
915 Effect.logError("Failed to inspect attachment asset.", {
916 attachmentId: claims.attachmentId,
917 path: attachmentPath,
918 cause,
919 }),
920 ),
921 Effect.orElseSucceed(() => Option.none()),
922 );
923 return Option.isSome(info) && info.value.type === "File"
924 ? ({
925 kind: "file",
926 path: attachmentPath,
927 ...(claims.download ? { download: true } : {}),
928 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
929 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
930 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
931 } satisfies ResolvedAsset)
932 : null;
933 }
934
935 if (claims.kind === "project-favicon") {
936 if (claims.relativePath === null) return null;
937 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
938 workspaceRoot: claims.workspaceRoot,
939 relativePath: claims.relativePath,
940 });
941 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
942 }
943
944 if (claims.kind === "project-favicon-external") {
945 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
946 Effect.tapError((cause) =>
947 Effect.logError("Failed to resolve canonical asset path.", {
948 filePath: claims.filePath,
949 cause,
950 }),
951 ),
952 Effect.orElseSucceed(() => null),
953 );
954 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
955 }
956
957 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
958 return {
959 kind: "source-control-media",
960 url: claims.url,
961 cwd: claims.cwd,
962 expiresAt: claims.expiresAt,
963 } satisfies ResolvedAsset;
964 }
965
966 if (claims.kind === "tool-output-image") {
967 const image = yield* readToolOutputImage(claims).pipe(
968 Effect.tapError((cause) =>
969 Effect.logError("Failed to read tool output image.", {
970 threadId: claims.threadId,
971 itemId: claims.itemId,
972 cause,
973 }),
974 ),
975 Effect.orElseSucceed(() => null),
976 );
977 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
978 }
979
980 if (claims.kind === "native-app-icon") {
981 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
982 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
983 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
984 }
985
986 const decodedPath = decodeRelativePath(relativePath);
987 if (decodedPath === null) return null;
988 const path = yield* Path.Path;
989 if (claims.kind === "media-file-exact") {
990 if (decodedPath !== path.basename(claims.filePath)) return null;
991 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
992 Effect.tapError((cause) =>
993 Effect.logError("Failed to resolve canonical media path.", {
994 filePath: claims.filePath,
995 cause,
996 }),
997 ),
998 Effect.orElseSucceed(() => null),
999 );
1000 if (canonicalFile !== claims.filePath) return null;
1001 const mimeType = claims.download
1002 ? "application/octet-stream"
1003 : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
1004 if (!mimeType) return null;
1005 const file = yield* openMediaFile(canonicalFile, claims).pipe(
1006 Effect.tapError((cause) =>
1007 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
1008 ),
1009 Effect.orElseSucceed(() => null),
1010 );
1011 return file
1012 ? ({
1013 kind: "file",
1014 path: canonicalFile,
1015 mimeType,
1016 file,
1017 ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
1018 } satisfies ResolvedAsset)
1019 : null;
1020 }
1021 if (claims.kind === "workspace-file-exact") {
1022 if (decodedPath !== path.basename(claims.relativePath)) return null;
1023 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1024 workspaceRoot: claims.workspaceRoot,
1025 relativePath: claims.relativePath,
1026 });
1027 return exactWorkspaceFile
1028 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
1029 : null;
1030 }
1031 const segments = decodedPath.split(/[\\/]/);
1032 if (
1033 decodedPath.length === 0 ||
1034 decodedPath.includes("\0") ||
1035 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
1036 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
1037 ) {
1038 return null;
1039 }
1040 const joinedRelativePath =
1041 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1042 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1043 workspaceRoot: claims.workspaceRoot,
1044 relativePath: joinedRelativePath,
1045 });
1046 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
1047});