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

AssetAccess.ts

1,165 lines42.5 KB

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