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

AssetAccess.ts

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