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

AssetAccess.ts

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