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

AssetAccess.ts

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