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

AssetAccess.ts

1,039 lines37.0 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* readImageDimensionsFromHeader(attachmentPath);
663 }
664 claims = {
665 version: 1,
666 kind: "attachment",
667 attachmentId: input.resource.attachmentId,
668 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
669 ? { download: true }
670 : {}),
671 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
672 ...(inlinePreviewMimeType !== undefined
673 ? { mimeType: inlinePreviewMimeType }
674 : input.resource.mimeType !== undefined
675 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
676 : {}),
677 ...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
678 ? { renderIntent: "mcp-app" as const }
679 : {}),
680 expiresAt,
681 };
682 fileName = input.resource.fileName ?? path.basename(attachmentPath);
683 break;
684 }
685 case "project-favicon": {
686 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
687 Effect.mapError(
688 (cause) =>
689 new AssetWorkspaceRootNormalizationError({
690 resource: input.resource,
691 cause,
692 }),
693 ),
694 );
695 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
696 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
697 // Once it lands, a miss cached before (by enrichment) is stale too.
698 if (input.projectCheckout === "cloned") yield* faviconResolver.invalidate(workspaceRoot);
699 const faviconPath =
700 input.projectCheckout === "pending"
701 ? null
702 : yield* faviconResolver
703 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
704 .pipe(
705 Effect.mapError(
706 (cause) =>
707 new AssetProjectFaviconResolutionError({
708 resource: input.resource,
709 cause,
710 }),
711 ),
712 );
713 const isExternalOverride =
714 faviconPath !== null &&
715 input.projectFaviconPath !== undefined &&
716 path.isAbsolute(input.projectFaviconPath) &&
717 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
718 const relativePath =
719 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
720 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
721 if (sourceFaviconPath && !isProjectFaviconPath(sourceFaviconPath)) {
722 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
723 }
724 sourcePath = sourceFaviconPath ?? undefined;
725 const canonicalFaviconPath = sourceFaviconPath
726 ? yield* (
727 isExternalOverride
728 ? resolveCanonicalFile(sourceFaviconPath)
729 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
730 ).pipe(
731 Effect.mapError(
732 (cause) =>
733 new AssetProjectFaviconInspectionError({
734 resource: input.resource,
735 cause,
736 }),
737 ),
738 )
739 : null;
740 if (sourceFaviconPath && !canonicalFaviconPath) {
741 return yield* new AssetProjectFaviconNotFoundError({
742 resource: input.resource,
743 });
744 }
745 claims =
746 isExternalOverride && canonicalFaviconPath
747 ? {
748 version: 1,
749 kind: "project-favicon-external",
750 filePath: canonicalFaviconPath,
751 expiresAt,
752 }
753 : {
754 version: 1,
755 kind: "project-favicon",
756 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
757 Effect.mapError(
758 (cause) =>
759 new AssetWorkspaceResolutionError({
760 resource: input.resource,
761 cause,
762 }),
763 ),
764 ),
765 relativePath,
766 expiresAt,
767 };
768 if (sourceFaviconPath && canonicalFaviconPath) {
769 const crypto = yield* Crypto.Crypto;
770 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
771 Effect.mapError(
772 (cause) =>
773 new AssetProjectFaviconInspectionError({
774 resource: input.resource,
775 cause,
776 }),
777 ),
778 );
779 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
780 Effect.map(Hex.encode),
781 Effect.mapError(
782 (cause) =>
783 new AssetProjectFaviconInspectionError({
784 resource: input.resource,
785 cause,
786 }),
787 ),
788 );
789 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
790 } else {
791 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
792 }
793 break;
794 }
795 case "tool-output-image": {
796 const image = yield* readToolOutputImage(input.resource).pipe(
797 Effect.mapError(
798 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
799 ),
800 );
801 if (image === null) {
802 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
803 }
804 claims = {
805 version: 1,
806 kind: "tool-output-image",
807 threadId: input.resource.threadId,
808 itemId: input.resource.itemId,
809 index: input.resource.index,
810 expiresAt,
811 };
812 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
813 imageDimensions = readImageDimensions(image.bytes);
814 break;
815 }
816 case "native-app-icon": {
817 claims = {
818 version: 1,
819 kind: "native-app-icon",
820 app: input.resource.app,
821 expiresAt,
822 };
823 fileName = "native-app-icon.png";
824 break;
825 }
826 case SOURCE_CONTROL_MEDIA_ASSET: {
827 const media = sourceControlDefinitions.mediaUrl(input.resource.url);
828 if (media === null) {
829 return yield* new AssetSourceControlMediaUrlValidationError({});
830 }
831 claims = {
832 version: 1,
833 kind: SOURCE_CONTROL_MEDIA_ASSET,
834 url: media.fetchUrl,
835 cwd: input.resource.cwd,
836 expiresAt,
837 };
838 fileName = media.fileName;
839 break;
840 }
841 }
842​
843 const secretStore = yield* ServerSecretStore.ServerSecretStore;
844 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
845 Effect.mapError(
846 (cause) =>
847 new AssetSigningKeyLoadError({
848 resource: input.resource,
849 cause,
850 }),
851 ),
852 );
853 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
854 const issuedAt = yield* Clock.currentTimeMillis;
855 expiresAt =
856 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
857 PROJECT_FAVICON_TOKEN_BUCKET_MS;
858 claims = { ...claims, expiresAt };
859 }
860 if (claims.kind === "attachment" && claims.mimeType === "text/html") {
861 // Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
862 expiresAt =
863 Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
864 claims = { ...claims, expiresAt };
865 }
866 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
867 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
868 return {
869 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
870 expiresAt,
871 ...(sourcePath !== undefined ? { sourcePath } : {}),
872 ...(imageDimensions !== null ? { imageDimensions } : {}),
873 ...(fileRevision !== undefined ? { fileRevision } : {}),
874 };
875});
876​
877export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
878 token: string,
879 relativePath: string,
880) {
881 const [encodedPayload, signature] = token.split(".");
882 if (!encodedPayload || !signature) return null;
883​
884 const secretStore = yield* ServerSecretStore.ServerSecretStore;
885 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
886 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
887 Effect.orElseSucceed(() => null),
888 );
889 if (!signingSecret) return null;
890 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
891​
892 const claims = decodeClaims(encodedPayload);
893 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
894​
895 if (claims.kind === "attachment") {
896 const config = yield* ServerConfig.ServerConfig;
897 const attachmentPath = resolveAttachmentPathById({
898 attachmentsDir: config.attachmentsDir,
899 attachmentId: claims.attachmentId,
900 });
901 if (!attachmentPath) return null;
902 const fileSystem = yield* FileSystem.FileSystem;
903 const info = yield* ProjectFaviconResolver.optionOnNotFound(
904 fileSystem.stat(attachmentPath),
905 ).pipe(
906 Effect.tapError((cause) =>
907 Effect.logError("Failed to inspect attachment asset.", {
908 attachmentId: claims.attachmentId,
909 path: attachmentPath,
910 cause,
911 }),
912 ),
913 Effect.orElseSucceed(() => Option.none()),
914 );
915 return Option.isSome(info) && info.value.type === "File"
916 ? ({
917 kind: "file",
918 path: attachmentPath,
919 ...(claims.download ? { download: true } : {}),
920 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
921 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
922 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
923 } satisfies ResolvedAsset)
924 : null;
925 }
926​
927 if (claims.kind === "project-favicon") {
928 if (claims.relativePath === null) return null;
929 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
930 workspaceRoot: claims.workspaceRoot,
931 relativePath: claims.relativePath,
932 });
933 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
934 }
935​
936 if (claims.kind === "project-favicon-external") {
937 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
938 Effect.tapError((cause) =>
939 Effect.logError("Failed to resolve canonical asset path.", {
940 filePath: claims.filePath,
941 cause,
942 }),
943 ),
944 Effect.orElseSucceed(() => null),
945 );
946 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
947 }
948​
949 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
950 return {
951 kind: "source-control-media",
952 url: claims.url,
953 cwd: claims.cwd,
954 expiresAt: claims.expiresAt,
955 } 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});