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