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

AssetAccess.ts

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