Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.ts

1,039 lines37.3 KB

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} from "@t3tools/contracts";
21import {
22 hostPreviewMimeTypeFromExtension,
23 isWorkspaceAudioPreviewPath,
24 isWorkspacePreviewEntryPath,
25 isWorkspaceVideoPreviewPath,
26 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
27} from "@t3tools/shared/filePreview";
28import {
29 IMAGE_DIMENSIONS_HEADER_BYTES,
30 readImageDimensions,
31 type ImageDimensions,
32} from "@t3tools/shared/imageDimensions";
33import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
34import {
35 isProjectFaviconPath,
36 PROJECT_FAVICON_FALLBACK_MARKER,
37} from "@t3tools/shared/projectFavicon";
38import { isNetworkPath } from "@t3tools/shared/path";
39import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
40import * as Clock from "effect/Clock";
41import * as Digest from "effect/crypto/Digest";
42import * as Effect from "effect/Effect";
43import * as Hex from "effect/encoding/Hex";
44import * as FileSystem from "effect/FileSystem";
45import * as Option from "effect/Option";
46import * as Path from "effect/Path";
47import * as Schema from "effect/Schema";
48import * as Stream from "effect/Stream";
49​
50import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
51import * as AssetSigner from "./AssetSigner.ts";
52import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
53import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
54import * as ServerConfig from "../config.ts";
55import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
56import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
57import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
58import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
59import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
60import { toWslDrivePath } from "../workspace/wslDrivePath.ts";
61import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
62import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
63import { extractIcnsPng } from "./icns.ts";
64import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
65import * as HostProcess from "@t3tools/shared/HostProcess";
66​
67export const ASSET_ROUTE_PREFIX = "/api/assets";
68​
69const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
70const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
71const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
72const PROJECT_FAVICON_VERSION_PREFIX = "v";
73const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
74const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
75// Use server-assigned attachment extensions, never client MIME types.
76const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
77 svg: "image/svg+xml",
78 pdf: "application/pdf",
79 html: "text/html",
80 htm: "text/html",
81};
82const inlinePreviewMimeTypeForExtension = (extension: string) =>
83 INLINE_PREVIEW_MIME_TYPES[extension] ??
84 hostPreviewMimeTypeFromExtension(`.${extension}`) ??
85 undefined;
86const PREVIEW_ASSET_EXTENSIONS = new Set([
87 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
88 // Keep HTML dependency grants independent of newly supported file viewers.
89 ".avif",
90 ".gif",
91 ".ico",
92 ".jpeg",
93 ".jpg",
94 ".png",
95 ".svg",
96 ".webp",
97 ".css",
98 ".js",
99 ".mjs",
100 ".otf",
101 ".ttf",
102 ".woff",
103 ".woff2",
104]);
105​
106const AssetClaimsSchema = Schema.Union([
107 Schema.Struct({
108 version: Schema.Literal(1),
109 kind: Schema.Literal("workspace-file"),
110 workspaceRoot: Schema.String,
111 baseRelativePath: Schema.String,
112 expiresAt: Schema.Number,
113 }),
114 Schema.Struct({
115 version: Schema.Literal(1),
116 kind: Schema.Literal("workspace-file-exact"),
117 workspaceRoot: Schema.String,
118 relativePath: Schema.String,
119 expiresAt: Schema.Number,
120 }),
121 Schema.Struct({
122 version: Schema.Literal(1),
123 kind: Schema.Literal("media-file-exact"),
124 filePath: Schema.String,
125 download: Schema.optionalKey(Schema.Boolean),
126 device: Schema.String,
127 inode: Schema.String,
128 expiresAt: Schema.Number,
129 }),
130 Schema.Struct({
131 version: Schema.Literal(1),
132 kind: Schema.Literal("attachment"),
133 attachmentId: Schema.String,
134 download: Schema.optionalKey(Schema.Boolean),
135 fileName: Schema.optionalKey(Schema.String),
136 mimeType: Schema.optionalKey(Schema.String),
137 renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
138 expiresAt: Schema.Number,
139 }),
140 Schema.Struct({
141 version: Schema.Literal(1),
142 kind: Schema.Literal("project-favicon"),
143 workspaceRoot: Schema.String,
144 relativePath: Schema.NullOr(Schema.String),
145 expiresAt: Schema.Number,
146 }),
147 Schema.Struct({
148 version: Schema.Literal(1),
149 kind: Schema.Literal("project-favicon-external"),
150 filePath: Schema.String,
151 expiresAt: Schema.Number,
152 }),
153 Schema.Struct({
154 version: Schema.Literal(1),
155 kind: Schema.Literal("native-app-icon"),
156 app: NativeAppIconReference,
157 expiresAt: Schema.Number,
158 }),
159 Schema.Struct({
160 version: Schema.Literal(1),
161 kind: Schema.Literal("tool-output-image"),
162 threadId: ThreadId,
163 itemId: TurnItemId,
164 index: Schema.Number,
165 expiresAt: Schema.Number,
166 }),
167 Schema.Struct({
168 version: Schema.Literal(1),
169 kind: Schema.Literal(SOURCE_CONTROL_MEDIA_ASSET),
170 /** A host's `fetchUrl`, narrowed at mint time; the signature is what keeps it there. */
171 url: Schema.String,
172 cwd: Schema.String,
173 repository: Schema.optionalKey(Schema.String),
174 expiresAt: Schema.Number,
175 }),
176]);
177type AssetClaims = typeof AssetClaimsSchema.Type;
178​
179const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
180const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
181const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
182​
183export type ResolvedAsset =
184 | {
185 readonly kind: "file";
186 readonly path: string;
187 readonly download?: boolean;
188 readonly fileName?: string;
189 readonly mimeType?: string;
190 readonly file?: OpenMediaFile;
191 readonly renderIntent?: "mcp-app";
192 }
193 | {
194 readonly kind: "bytes";
195 readonly bytes: Uint8Array;
196 readonly mimeType: string;
197 }
198 | {
199 readonly kind: "source-control-media";
200 readonly url: string;
201 readonly cwd: string;
202 readonly repository?: string;
203 readonly expiresAt: number;
204 };
205​
206function decodeClaims(encodedPayload: string): AssetClaims | null {
207 try {
208 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
209 } catch {
210 return null;
211 }
213​
214function decodeRelativePath(value: string): string | null {
215 try {
216 return decodeURIComponent(value);
217 } catch {
218 return null;
219 }
221​
222export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
223 const fileSystem = yield* FileSystem.FileSystem;
224 // Allow space for stored CSP tags, but bound reads if the attachment grows after minting.
225 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
226 const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
227 const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
228 if (size > limit) return null;
229 const bytes = new Uint8Array(size);
230 let position = 0;
231 for (const chunk of chunks) {
232 bytes.set(chunk, position);
233 position += chunk.byteLength;
234 }
235 return bytes;
236});
237​
238const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
239 readonly threadId: ThreadId;
240 readonly itemId: TurnItemId;
241 readonly index: number;
242}) {
243 const orchestrator = yield* Orchestrator.OrchestratorV2;
244 const item = yield* orchestrator.getTurnItem(input);
245 const image =
246 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
247 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
248 ? null
249 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
250});
251​
252// Browsers cannot draw .icns; serve its embedded PNG.
253const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* (
254 filePath: string,
255) {
256 if (!filePath.toLowerCase().endsWith(".icns")) {
257 return { kind: "file", path: filePath } satisfies ResolvedAsset;
258 }
259 const fileSystem = yield* FileSystem.FileSystem;
260 const bytes = yield* fileSystem.readFile(filePath).pipe(
261 Effect.tapError((cause) =>
262 Effect.logError("Failed to read project icon image.", { filePath, cause }),
263 ),
264 Effect.orElseSucceed(() => null),
265 );
266 const png = bytes ? extractIcnsPng(bytes, PROJECT_FAVICON_ICNS_MIN_SIZE) : null;
267 return png
268 ? ({ kind: "bytes", bytes: png, mimeType: "image/png" } satisfies ResolvedAsset)
269 : null;
270});
271​
272const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
273 filePath: string,
274) {
275 const fileSystem = yield* FileSystem.FileSystem;
276 const canonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
277 fileSystem.realPath(filePath),
278 );
279 if (Option.isNone(canonicalFile)) return null;
280​
281 const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
282 if (Option.isNone(info) || info.value.type !== "File") return null;
283 const isServerInternalPath = yield* makeIsServerInternalPath;
284 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
285});
286​
287const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
288 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
289 const fileSystem = yield* FileSystem.FileSystem;
290 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
291 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
292 Effect.asSome,
293 Effect.catchTags({
294 WorkspacePathOutsideRootError: () => Effect.succeedNone,
295 }),
296 );
297 if (Option.isNone(resolved)) return null;
298​
299 const [canonicalRoot, canonicalFile] = yield* Effect.all([
300 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
301 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
302 ]);
303 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
304​
305 const path = yield* Path.Path;
306 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
307 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
308​
309 const info = yield* ProjectFaviconResolver.optionOnNotFound(
310 fileSystem.stat(canonicalFile.value),
311 );
312 if (Option.isNone(info) || info.value.type !== "File") return null;
313 const isServerInternalPath = yield* makeIsServerInternalPath;
314 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
315 },
316);
317​
318const resolveCanonicalWorkspaceFileForRequest = (input: {
319 readonly workspaceRoot: string;
320 readonly relativePath: string;
321}) =>
322 resolveCanonicalWorkspaceFile(input).pipe(
323 Effect.tapError((cause) =>
324 Effect.logError("Failed to resolve canonical asset path.", {
325 workspaceRoot: input.workspaceRoot,
326 relativePath: input.relativePath,
327 cause,
328 }),
329 ),
330 Effect.orElseSucceed(() => null),
331 );
332​
333const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
334​
335const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
336 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
337 Effect.map(readImageDimensions),
338 Effect.orElseSucceed((): ImageDimensions | null => null),
339 );
340​
341// Non-blocking open prevents swapped-in FIFOs from hanging the request.
342const readImageDimensionsFromHeader = (filePath: string) =>
343 openMediaFile(filePath).pipe(
344 Effect.flatMap((file) =>
345 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
346 ),
347 Effect.scoped,
348 Effect.orElseSucceed((): ImageDimensions | null => null),
349 );
350​
351const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
352 function* (input: {
353 readonly requestedPath: string;
354 readonly expectedCanonicalPath?: string;
355 readonly workspaceRoot: string | undefined;
356 readonly resource: AssetResource;
357 readonly expiresAt: number;
358 }) {
359 const path = yield* Path.Path;
360 // Resolving a network path makes Windows sign in to its host with the
361 // user's NTLM credentials, so only the thread's own project may be on a share.
362 // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
363 // the resolved path this check approved.
364 const requestedPath = path.resolve(input.requestedPath);
365 if (
366 isNetworkPath(input.requestedPath) &&
367 (input.workspaceRoot === undefined ||
368 !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
369 ) {
370 return yield* new AssetWorkspaceAssetNotFoundError({
371 resource: input.resource,
372 checkedPath: input.requestedPath,
373 });
374 }
375 const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
376 Effect.mapError(
377 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
378 ),
379 );
380 // The workspace caller pins its containment-checked path; never follow a
381 // replacement symlink to a different file during this second resolution.
382 if (
383 !canonicalFile ||
384 (input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
385 ) {
386 return yield* new AssetWorkspaceAssetNotFoundError({
387 resource: input.resource,
388 checkedPath: input.requestedPath,
389 });
390 }
391 const download =
392 input.resource._tag === "media-file" && input.resource.disposition === "attachment";
393 if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
394 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
395 }
396 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
397 const opened = yield* openMediaFile(canonicalFile).pipe(
398 Effect.flatMap((file) =>
399 file === null
400 ? Effect.succeed(null)
401 : Effect.map(
402 wantsDimensions
403 ? readImageDimensionsFromOpenFile(canonicalFile, file)
404 : Effect.succeed(null),
405 (dimensions) => ({
406 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
407 fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
408 dimensions,
409 }),
410 ),
411 ),
412 Effect.scoped,
413 Effect.mapError(
414 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
415 ),
416 );
417 if (!opened) {
418 return yield* new AssetWorkspaceAssetNotFoundError({
419 resource: input.resource,
420 checkedPath: input.requestedPath,
421 });
422 }
423 return {
424 claims: {
425 version: 1 as const,
426 kind: "media-file-exact" as const,
427 filePath: canonicalFile,
428 ...(download ? { download: true } : {}),
429 ...opened.identity,
430 expiresAt: input.expiresAt,
431 },
432 fileName: path.basename(canonicalFile),
433 fileRevision: opened.fileRevision,
434 imageDimensions: opened.dimensions,
435 };
436 },
437);
438​
439const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
440 function* (input: {
441 readonly workspaceRoot: string;
442 readonly requestedPath: string;
443 readonly resource: AssetResource;
444 readonly expiresAt: number;
445 }) {
446 const path = yield* Path.Path;
447 const fileSystem = yield* FileSystem.FileSystem;
448 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
449 const relativePath = path.isAbsolute(input.requestedPath)
450 ? path.relative(input.workspaceRoot, input.requestedPath)
451 : input.requestedPath;
452 const resolved = yield* workspacePaths
453 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
454 .pipe(
455 Effect.mapError(
456 (cause) =>
457 new AssetWorkspacePathValidationError({
458 resource: input.resource,
459 cause,
460 }),
461 ),
462 );
463 const isDraftMedia =
464 input.resource._tag === "draft-workspace-file" &&
465 (isWorkspaceAudioPreviewPath(resolved.relativePath) ||
466 isWorkspaceVideoPreviewPath(resolved.relativePath));
467 if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
468 return yield* new AssetPreviewTypeValidationError({
469 resource: input.resource,
470 });
471 }
472 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
473 workspaceRoot: input.workspaceRoot,
474 relativePath: resolved.relativePath,
475 }).pipe(
476 Effect.mapError(
477 (cause) =>
478 new AssetWorkspaceAssetInspectionError({
479 resource: input.resource,
480 cause,
481 }),
482 ),
483 );
484 if (!canonicalFile) {
485 return yield* new AssetWorkspaceAssetNotFoundError({
486 resource: input.resource,
487 });
488 }
489 if (isDraftMedia) {
490 return yield* finalizeAbsoluteMediaFileAsset({
491 ...input,
492 requestedPath: canonicalFile,
493 expectedCanonicalPath: canonicalFile,
494 });
495 }
496 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
497 Effect.mapError(
498 (cause) =>
499 new AssetWorkspaceResolutionError({
500 resource: input.resource,
501 cause,
502 }),
503 ),
504 );
505 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
506 path.extname(resolved.relativePath).toLowerCase(),
507 )
508 ? yield* readImageDimensionsFromHeader(canonicalFile)
509 : null;
510 return {
511 claims: !/\.html?$/i.test(resolved.relativePath)
512 ? {
513 version: 1 as const,
514 kind: "workspace-file-exact" as const,
515 workspaceRoot: canonicalWorkspaceRoot,
516 relativePath: resolved.relativePath,
517 expiresAt: input.expiresAt,
518 }
519 : {
520 version: 1 as const,
521 kind: "workspace-file" as const,
522 workspaceRoot: canonicalWorkspaceRoot,
523 baseRelativePath: path.dirname(resolved.relativePath),
524 expiresAt: input.expiresAt,
525 },
526 fileName: path.basename(resolved.relativePath),
527 imageDimensions,
528 fileRevision: undefined,
529 };
530 },
531);
532​
533export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
534 readonly resource: AssetResource;
535 readonly workspaceRoot?: string;
536 readonly projectFaviconPath?: string;
537 /** Where a cloned project's checkout stands, while the clone tracker still knows it. */
538 readonly projectCheckout?: "pending" | "cloned";
539}) {
540 const fileSystem = yield* FileSystem.FileSystem;
541 const path = yield* Path.Path;
542 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
543 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
544 let claims: AssetClaims;
545 let fileName: string;
546 let sourcePath: string | undefined;
547 let imageDimensions: ImageDimensions | null = null;
548 let fileRevision: string | undefined;
549​
550 switch (input.resource._tag) {
551 case "media-file": {
552 let requestedPath = expandHomePath(
553 yield* toWslDrivePath(input.resource.path),
554 yield* HostProcess.HomeDirectory,
555 );
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 : yield* toWslDrivePath(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 const { _tag, ...resource } = input.resource;
840 claims = {
841 version: 1,
842 kind: SOURCE_CONTROL_MEDIA_ASSET,
843 ...resource,
844 url: media.fetchUrl,
845 expiresAt,
846 };
847 fileName = media.fileName;
848 break;
849 }
850 }
851​
852 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
853 const issuedAt = yield* Clock.currentTimeMillis;
854 expiresAt =
855 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
856 PROJECT_FAVICON_TOKEN_BUCKET_MS;
857 claims = { ...claims, expiresAt };
858 }
859 if (claims.kind === "attachment" && claims.mimeType === "text/html") {
860 // Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
861 expiresAt =
862 Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
863 claims = { ...claims, expiresAt };
864 }
865 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
866 const signer = yield* AssetSigner.AssetSigner;
867 const signature = yield* signer
868 .sign(encodedPayload)
869 .pipe(
870 Effect.mapError((cause) => new AssetSigningKeyLoadError({ resource: input.resource, cause })),
871 );
872 const token = `${encodedPayload}.${signature}`;
873 return {
874 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
875 expiresAt,
876 ...(sourcePath !== undefined ? { sourcePath } : {}),
877 ...(imageDimensions !== null ? { imageDimensions } : {}),
878 ...(fileRevision !== undefined ? { fileRevision } : {}),
879 };
880});
881​
882export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
883 token: string,
884 relativePath: string,
885) {
886 const [encodedPayload, signature] = token.split(".");
887 if (!encodedPayload || !signature) return null;
888​
889 const signer = yield* AssetSigner.AssetSigner;
890 const verified = yield* signer.verify(encodedPayload, signature).pipe(
891 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
892 Effect.orElseSucceed(() => false),
893 );
894 if (!verified) return null;
895​
896 const claims = decodeClaims(encodedPayload);
897 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
898​
899 if (claims.kind === "attachment") {
900 const config = yield* ServerConfig.ServerConfig;
901 const attachmentPath = resolveAttachmentPathById({
902 attachmentsDir: config.attachmentsDir,
903 attachmentId: claims.attachmentId,
904 });
905 if (!attachmentPath) return null;
906 const fileSystem = yield* FileSystem.FileSystem;
907 const info = yield* ProjectFaviconResolver.optionOnNotFound(
908 fileSystem.stat(attachmentPath),
909 ).pipe(
910 Effect.tapError((cause) =>
911 Effect.logError("Failed to inspect attachment asset.", {
912 attachmentId: claims.attachmentId,
913 path: attachmentPath,
914 cause,
915 }),
916 ),
917 Effect.orElseSucceed(() => Option.none()),
918 );
919 return Option.isSome(info) && info.value.type === "File"
920 ? ({
921 kind: "file",
922 path: attachmentPath,
923 ...(claims.download ? { download: true } : {}),
924 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
925 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
926 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
927 } satisfies ResolvedAsset)
928 : null;
929 }
930​
931 if (claims.kind === "project-favicon") {
932 if (claims.relativePath === null) return null;
933 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
934 workspaceRoot: claims.workspaceRoot,
935 relativePath: claims.relativePath,
936 });
937 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
938 }
939​
940 if (claims.kind === "project-favicon-external") {
941 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
942 Effect.tapError((cause) =>
943 Effect.logError("Failed to resolve canonical asset path.", {
944 filePath: claims.filePath,
945 cause,
946 }),
947 ),
948 Effect.orElseSucceed(() => null),
949 );
950 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
951 }
952​
953 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
954 const { version: _version, ...media } = claims;
955 return { ...media, kind: "source-control-media" } satisfies ResolvedAsset;
956 }
957​
958 if (claims.kind === "tool-output-image") {
959 const image = yield* readToolOutputImage(claims).pipe(
960 Effect.tapError((cause) =>
961 Effect.logError("Failed to read tool output image.", {
962 threadId: claims.threadId,
963 itemId: claims.itemId,
964 cause,
965 }),
966 ),
967 Effect.orElseSucceed(() => null),
968 );
969 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
970 }
971​
972 if (claims.kind === "native-app-icon") {
973 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
974 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
975 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
976 }
977​
978 const decodedPath = decodeRelativePath(relativePath);
979 if (decodedPath === null) return null;
980 const path = yield* Path.Path;
981 if (claims.kind === "media-file-exact") {
982 if (decodedPath !== path.basename(claims.filePath)) return null;
983 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
984 Effect.tapError((cause) =>
985 Effect.logError("Failed to resolve canonical media path.", {
986 filePath: claims.filePath,
987 cause,
988 }),
989 ),
990 Effect.orElseSucceed(() => null),
991 );
992 if (canonicalFile !== claims.filePath) return null;
993 const mimeType = claims.download
994 ? "application/octet-stream"
995 : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
996 if (!mimeType) return null;
997 const file = yield* openMediaFile(canonicalFile, claims).pipe(
998 Effect.tapError((cause) =>
999 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
1000 ),
1001 Effect.orElseSucceed(() => null),
1002 );
1003 return file
1004 ? ({
1005 kind: "file",
1006 path: canonicalFile,
1007 mimeType,
1008 file,
1009 ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
1010 } satisfies ResolvedAsset)
1011 : null;
1013 if (claims.kind === "workspace-file-exact") {
1014 if (decodedPath !== path.basename(claims.relativePath)) return null;
1015 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1016 workspaceRoot: claims.workspaceRoot,
1017 relativePath: claims.relativePath,
1018 });
1019 return exactWorkspaceFile
1020 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
1021 : null;
1023 const segments = decodedPath.split(/[\\/]/);
1024 if (
1025 decodedPath.length === 0 ||
1026 decodedPath.includes("\0") ||
1027 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
1028 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
1029 ) {
1030 return null;
1032 const joinedRelativePath =
1033 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1034 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1035 workspaceRoot: claims.workspaceRoot,
1036 relativePath: joinedRelativePath,
1037 });
1038 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
1039});