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