The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,147 lines 41.3 KB
Raw
1 import type { AssetResource } from "@t3tools/contracts";
2 import {
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";
22 import {
23 hostPreviewMimeTypeFromExtension,
24 isWorkspaceAudioPreviewPath,
25 isWorkspacePreviewEntryPath,
26 isWorkspaceVideoPreviewPath,
27 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
28 } from "@t3tools/shared/filePreview";
29 import {
30 IMAGE_DIMENSIONS_HEADER_BYTES,
31 readImageDimensions,
32 type ImageDimensions,
33 } from "@t3tools/shared/imageDimensions";
34 import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
35 import {
36 isProjectFaviconPath,
37 PROJECT_FAVICON_FALLBACK_MARKER,
38 } from "@t3tools/shared/projectFavicon";
39 import { isNetworkPath } from "@t3tools/shared/path";
40 import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
41 import * as Clock from "effect/Clock";
42 import * as Digest from "effect/crypto/Digest";
43 import * as Effect from "effect/Effect";
44 import * as Hex from "effect/encoding/Hex";
45 import * as FileSystem from "effect/FileSystem";
46 import * as Option from "effect/Option";
47 import * as Path from "effect/Path";
48 import * as Schema from "effect/Schema";
49 import * as Stream from "effect/Stream";
50
51 import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
52 import * as AssetSigner from "./AssetSigner.ts";
53 import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
54 import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
55 import * as ServerConfig from "../config.ts";
56 import { findThemeBackground } from "../environmentTheme.ts";
57 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
58 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
59 import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
60 import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
61 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
62 import { toHostDrivePath } from "../workspace/hostDrivePath.ts";
63 import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
64 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
65 import { extractIcnsPng } from "./icns.ts";
66 import {
67 mediaFileRevision,
68 openMediaFile,
69 readMediaFileHeader,
70 type OpenMediaFile,
71 } from "./MediaFile.ts";
72 import * as WorkspacePreviewRevisions from "./WorkspacePreviewRevisions.ts";
73 import * as HostProcess from "@t3tools/shared/HostProcess";
74
75 export const ASSET_ROUTE_PREFIX = "/api/assets";
76
77 const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
78 const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
79 const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
80 const PROJECT_FAVICON_VERSION_PREFIX = "v";
81 const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
82 const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
83 // Use server-assigned attachment extensions, never client MIME types.
84 const 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 };
90 const inlinePreviewMimeTypeForExtension = (extension: string) =>
91 INLINE_PREVIEW_MIME_TYPES[extension] ??
92 hostPreviewMimeTypeFromExtension(`.${extension}`) ??
93 undefined;
94 const 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
126 const 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
132 const 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 ]);
211 type AssetClaims = typeof AssetClaimsSchema.Type;
212
213 const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
214 const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
215 const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
216
217 export 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
240 function decodeClaims(encodedPayload: string): AssetClaims | null {
241 try {
242 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
243 } catch {
244 return null;
245 }
246 }
247
248 function decodeRelativePath(value: string): string | null {
249 try {
250 return decodeURIComponent(value);
251 } catch {
252 return null;
253 }
254 }
255
256 export 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
272 const 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.
287 const 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
306 const 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
321 const 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
370 const 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
386 const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
387
388 const 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.
395 const 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
404 const 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.disposition === "attachment";
446 if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
447 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
448 }
449 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
450 const opened = yield* openMediaFile(canonicalFile).pipe(
451 Effect.flatMap((file) =>
452 file === null
453 ? Effect.succeed(null)
454 : Effect.map(
455 wantsDimensions
456 ? readImageDimensionsFromOpenFile(canonicalFile, file)
457 : Effect.succeed(null),
458 (dimensions) => ({
459 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
460 fileRevision: mediaFileRevision(file.info),
461 dimensions,
462 }),
463 ),
464 ),
465 Effect.scoped,
466 Effect.mapError(
467 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
468 ),
469 );
470 if (!opened) {
471 return yield* new AssetWorkspaceAssetNotFoundError({
472 resource: input.resource,
473 checkedPath: input.requestedPath,
474 });
475 }
476 return {
477 claims: {
478 version: 1 as const,
479 kind: "media-file-exact" as const,
480 filePath: canonicalFile,
481 ...(download ? { download: true } : {}),
482 ...opened.identity,
483 expiresAt: input.expiresAt,
484 },
485 fileName: path.basename(canonicalFile),
486 fileRevision: opened.fileRevision,
487 imageDimensions: opened.dimensions,
488 };
489 },
490 );
491
492 const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
493 function* (input: {
494 readonly workspaceRoot: string;
495 readonly requestedPath: string;
496 readonly resource: AssetResource;
497 readonly expiresAt: number;
498 }) {
499 const path = yield* Path.Path;
500 const fileSystem = yield* FileSystem.FileSystem;
501 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
502 const relativePath = path.isAbsolute(input.requestedPath)
503 ? path.relative(input.workspaceRoot, input.requestedPath)
504 : input.requestedPath;
505 const resolved = yield* workspacePaths
506 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
507 .pipe(
508 Effect.mapError(
509 (cause) =>
510 new AssetWorkspacePathValidationError({
511 resource: input.resource,
512 cause,
513 }),
514 ),
515 );
516 const isDraftMedia =
517 input.resource._tag === "draft-workspace-file" &&
518 (isWorkspaceAudioPreviewPath(resolved.relativePath) ||
519 isWorkspaceVideoPreviewPath(resolved.relativePath));
520 if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
521 return yield* new AssetPreviewTypeValidationError({
522 resource: input.resource,
523 });
524 }
525 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
526 workspaceRoot: input.workspaceRoot,
527 relativePath: resolved.relativePath,
528 }).pipe(
529 Effect.mapError(
530 (cause) =>
531 new AssetWorkspaceAssetInspectionError({
532 resource: input.resource,
533 cause,
534 }),
535 ),
536 );
537 if (!canonicalFile) {
538 return yield* new AssetWorkspaceAssetNotFoundError({
539 resource: input.resource,
540 });
541 }
542 if (isDraftMedia) {
543 return yield* finalizeAbsoluteMediaFileAsset({
544 ...input,
545 requestedPath: canonicalFile,
546 expectedCanonicalPath: canonicalFile,
547 });
548 }
549 // The response type follows the file a link points at, so that file must be previewable too.
550 if (!isWorkspacePreviewEntryPath(canonicalFile)) {
551 return yield* new AssetPreviewTypeValidationError({
552 resource: input.resource,
553 });
554 }
555 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
556 Effect.mapError(
557 (cause) =>
558 new AssetWorkspaceResolutionError({
559 resource: input.resource,
560 cause,
561 }),
562 ),
563 );
564 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
565 path.extname(resolved.relativePath).toLowerCase(),
566 )
567 ? yield* readImageDimensionsFromHeader(canonicalFile)
568 : null;
569 if (!/\.html?$/i.test(resolved.relativePath)) {
570 return {
571 claims: {
572 version: 1 as const,
573 kind: "workspace-file-exact" as const,
574 workspaceRoot: canonicalWorkspaceRoot,
575 relativePath: resolved.relativePath,
576 expiresAt: input.expiresAt,
577 },
578 fileName: path.basename(resolved.relativePath),
579 imageDimensions,
580 fileRevision: undefined,
581 };
582 }
583 const revisions = yield* WorkspacePreviewRevisions.WorkspacePreviewRevisions;
584 return {
585 claims: {
586 version: 1 as const,
587 kind: "workspace-file" as const,
588 workspaceRoot: canonicalWorkspaceRoot,
589 baseRelativePath: path.dirname(resolved.relativePath),
590 entryFileName: path.basename(resolved.relativePath),
591 expiresAt: input.expiresAt,
592 },
593 fileName: path.basename(resolved.relativePath),
594 imageDimensions,
595 fileRevision: yield* revisions.revision({
596 workspaceRoot: canonicalWorkspaceRoot,
597 entryRelativePath: resolved.relativePath,
598 }),
599 };
600 },
601 );
602
603 export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
604 readonly resource: AssetResource;
605 readonly workspaceRoot?: string;
606 readonly projectFaviconPath?: string;
607 /** Where a cloned project's checkout stands, while the clone tracker still knows it. */
608 readonly projectCheckout?: "pending" | "cloned";
609 }) {
610 const fileSystem = yield* FileSystem.FileSystem;
611 const path = yield* Path.Path;
612 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
613 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
614 let claims: AssetClaims;
615 let fileName: string;
616 let sourcePath: string | undefined;
617 let imageDimensions: ImageDimensions | null = null;
618 let fileRevision: string | undefined;
619
620 switch (input.resource._tag) {
621 case "media-file": {
622 let requestedPath = expandHomePath(
623 yield* toHostDrivePath(input.resource.path),
624 yield* HostProcess.HomeDirectory,
625 );
626 if (!path.isAbsolute(requestedPath)) {
627 if (!input.workspaceRoot) {
628 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
629 }
630 const workspaceRoot = yield* workspacePaths
631 .normalizeWorkspaceRoot(input.workspaceRoot)
632 .pipe(
633 Effect.mapError(
634 (cause) =>
635 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
636 ),
637 );
638 requestedPath = path.resolve(workspaceRoot, requestedPath);
639 }
640 const finalized = yield* finalizeAbsoluteMediaFileAsset({
641 requestedPath,
642 workspaceRoot: input.workspaceRoot,
643 resource: input.resource,
644 expiresAt,
645 });
646 claims = finalized.claims;
647 fileName = finalized.fileName;
648 imageDimensions = finalized.imageDimensions;
649 fileRevision = finalized.fileRevision;
650 break;
651 }
652 case "workspace-file": {
653 if (!input.workspaceRoot) {
654 return yield* new AssetWorkspaceContextNotFoundError({
655 resource: input.resource,
656 });
657 }
658 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
659 Effect.mapError(
660 (cause) =>
661 new AssetWorkspaceRootNormalizationError({
662 resource: input.resource,
663 cause,
664 }),
665 ),
666 );
667 const finalized = yield* finalizeWorkspaceFileAsset({
668 workspaceRoot,
669 requestedPath: input.resource.path,
670 resource: input.resource,
671 expiresAt,
672 });
673 claims = finalized.claims;
674 fileName = finalized.fileName;
675 imageDimensions = finalized.imageDimensions;
676 fileRevision = finalized.fileRevision;
677 break;
678 }
679 case "draft-workspace-file": {
680 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
681 const hostPath =
682 input.resource.path.startsWith("~/") || input.resource.path.startsWith("~\\")
683 ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
684 : yield* toHostDrivePath(input.resource.path);
685 if (path.isAbsolute(hostPath)) {
686 const finalized = yield* finalizeAbsoluteMediaFileAsset({
687 requestedPath: hostPath,
688 workspaceRoot: draftWorkspaceRoot,
689 resource: input.resource,
690 expiresAt,
691 });
692 claims = finalized.claims;
693 fileName = finalized.fileName;
694 imageDimensions = finalized.imageDimensions;
695 fileRevision = finalized.fileRevision;
696 break;
697 }
698 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
699 Effect.mapError(
700 (cause) =>
701 new AssetWorkspaceRootNormalizationError({
702 resource: input.resource,
703 cause,
704 }),
705 ),
706 );
707 const finalized = yield* finalizeWorkspaceFileAsset({
708 workspaceRoot,
709 requestedPath: input.resource.path,
710 resource: input.resource,
711 expiresAt,
712 });
713 claims = finalized.claims;
714 fileName = finalized.fileName;
715 imageDimensions = finalized.imageDimensions;
716 fileRevision = finalized.fileRevision;
717 break;
718 }
719 case "attachment": {
720 const config = yield* ServerConfig.ServerConfig;
721 const attachmentPath = resolveAttachmentPathById({
722 attachmentsDir: config.attachmentsDir,
723 attachmentId: input.resource.attachmentId,
724 });
725 if (!attachmentPath) {
726 return yield* new AssetAttachmentNotFoundError({
727 resource: input.resource,
728 });
729 }
730 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
731 const isGenericFile = extension !== null;
732 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
733 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
734 const inlinePreviewMimeType =
735 input.resource.disposition === "inline" && extension !== null
736 ? inlinePreviewMimeTypeForExtension(extension)
737 : undefined;
738 if (!isGenericFile) {
739 imageDimensions = yield* fileSystem.realPath(attachmentPath).pipe(
740 Effect.flatMap(readImageDimensionsFromHeader),
741 Effect.orElseSucceed(() => null),
742 );
743 }
744 claims = {
745 version: 1,
746 kind: "attachment",
747 attachmentId: input.resource.attachmentId,
748 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
749 ? { download: true }
750 : {}),
751 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
752 ...(inlinePreviewMimeType !== undefined
753 ? { mimeType: inlinePreviewMimeType }
754 : input.resource.mimeType !== undefined
755 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
756 : {}),
757 ...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
758 ? { renderIntent: "mcp-app" as const }
759 : {}),
760 expiresAt,
761 };
762 fileName = input.resource.fileName ?? path.basename(attachmentPath);
763 break;
764 }
765 case "project-favicon": {
766 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
767 Effect.mapError(
768 (cause) =>
769 new AssetWorkspaceRootNormalizationError({
770 resource: input.resource,
771 cause,
772 }),
773 ),
774 );
775 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
776 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
777 // Once it lands, a miss cached before (by enrichment) is stale too.
778 if (input.projectCheckout === "cloned") yield* faviconResolver.invalidate(workspaceRoot);
779 const faviconPath =
780 input.projectCheckout === "pending"
781 ? null
782 : yield* faviconResolver
783 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
784 .pipe(
785 Effect.mapError(
786 (cause) =>
787 new AssetProjectFaviconResolutionError({
788 resource: input.resource,
789 cause,
790 }),
791 ),
792 );
793 const isExternalOverride =
794 faviconPath !== null &&
795 input.projectFaviconPath !== undefined &&
796 path.isAbsolute(input.projectFaviconPath) &&
797 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
798 const relativePath =
799 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
800 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
801 if (sourceFaviconPath && !isProjectFaviconPath(sourceFaviconPath)) {
802 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
803 }
804 sourcePath = sourceFaviconPath ?? undefined;
805 const canonicalFaviconPath = sourceFaviconPath
806 ? yield* (
807 isExternalOverride
808 ? resolveCanonicalFile(sourceFaviconPath)
809 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
810 ).pipe(
811 Effect.mapError(
812 (cause) =>
813 new AssetProjectFaviconInspectionError({
814 resource: input.resource,
815 cause,
816 }),
817 ),
818 )
819 : null;
820 if (sourceFaviconPath && !canonicalFaviconPath) {
821 return yield* new AssetProjectFaviconNotFoundError({
822 resource: input.resource,
823 });
824 }
825 claims =
826 isExternalOverride && canonicalFaviconPath
827 ? {
828 version: 1,
829 kind: "project-favicon-external",
830 filePath: canonicalFaviconPath,
831 expiresAt,
832 }
833 : {
834 version: 1,
835 kind: "project-favicon",
836 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
837 Effect.mapError(
838 (cause) =>
839 new AssetWorkspaceResolutionError({
840 resource: input.resource,
841 cause,
842 }),
843 ),
844 ),
845 relativePath,
846 expiresAt,
847 };
848 if (sourceFaviconPath && canonicalFaviconPath) {
849 const digest = yield* Digest.Digest;
850 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
851 Effect.mapError(
852 (cause) =>
853 new AssetProjectFaviconInspectionError({
854 resource: input.resource,
855 cause,
856 }),
857 ),
858 );
859 const revision = yield* digest.digest(Digest.sha256, faviconBytes).pipe(
860 Effect.map(Hex.encode),
861 Effect.mapError(
862 (cause) =>
863 new AssetProjectFaviconInspectionError({
864 resource: input.resource,
865 cause,
866 }),
867 ),
868 );
869 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
870 } else {
871 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
872 }
873 break;
874 }
875 case "tool-output-image": {
876 const image = yield* readToolOutputImage(input.resource).pipe(
877 Effect.mapError(
878 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
879 ),
880 );
881 if (image === null) {
882 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
883 }
884 claims = {
885 version: 1,
886 kind: "tool-output-image",
887 threadId: input.resource.threadId,
888 itemId: input.resource.itemId,
889 index: input.resource.index,
890 expiresAt,
891 };
892 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
893 imageDimensions = readImageDimensions(image.bytes);
894 break;
895 }
896 case "environment-theme-background": {
897 // Published themes go to every client, so any client may read their backgrounds.
898 claims = {
899 version: 1,
900 kind: "environment-theme-background",
901 themeId: input.resource.themeId,
902 expiresAt,
903 };
904 fileName = `${input.resource.themeId}-background`;
905 break;
906 }
907 case "native-app-icon": {
908 claims = {
909 version: 1,
910 kind: "native-app-icon",
911 app: input.resource.app,
912 expiresAt,
913 };
914 fileName = "native-app-icon.png";
915 break;
916 }
917 case SOURCE_CONTROL_MEDIA_ASSET: {
918 const media = sourceControlDefinitions.mediaUrl(input.resource.url);
919 if (media === null) {
920 return yield* new AssetSourceControlMediaUrlValidationError({});
921 }
922 const { _tag, ...resource } = input.resource;
923 claims = {
924 version: 1,
925 kind: SOURCE_CONTROL_MEDIA_ASSET,
926 ...resource,
927 url: media.fetchUrl,
928 expiresAt,
929 };
930 fileName = media.fileName;
931 break;
932 }
933 }
934
935 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
936 const issuedAt = yield* Clock.currentTimeMillis;
937 expiresAt =
938 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
939 PROJECT_FAVICON_TOKEN_BUCKET_MS;
940 claims = { ...claims, expiresAt };
941 }
942 if (claims.kind === "attachment" && claims.mimeType === "text/html") {
943 // Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
944 expiresAt =
945 Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
946 claims = { ...claims, expiresAt };
947 }
948 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
949 const signer = yield* AssetSigner.AssetSigner;
950 const signature = yield* signer
951 .sign(encodedPayload)
952 .pipe(
953 Effect.mapError((cause) => new AssetSigningKeyLoadError({ resource: input.resource, cause })),
954 );
955 const token = `${encodedPayload}.${signature}`;
956 return {
957 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
958 expiresAt,
959 ...(sourcePath !== undefined ? { sourcePath } : {}),
960 ...(imageDimensions !== null ? { imageDimensions } : {}),
961 ...(fileRevision !== undefined ? { fileRevision } : {}),
962 };
963 });
964
965 export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
966 token: string,
967 relativePath: string,
968 ) {
969 const [encodedPayload, signature] = token.split(".");
970 if (!encodedPayload || !signature) return null;
971
972 const signer = yield* AssetSigner.AssetSigner;
973 const verified = yield* signer.verify(encodedPayload, signature).pipe(
974 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
975 Effect.orElseSucceed(() => false),
976 );
977 if (!verified) return null;
978
979 const claims = decodeClaims(encodedPayload);
980 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
981
982 if (claims.kind === "attachment") {
983 const config = yield* ServerConfig.ServerConfig;
984 const attachmentPath = resolveAttachmentPathById({
985 attachmentsDir: config.attachmentsDir,
986 attachmentId: claims.attachmentId,
987 });
988 if (!attachmentPath) return null;
989 const fileSystem = yield* FileSystem.FileSystem;
990 const info = yield* ProjectFaviconResolver.optionOnNotFound(
991 fileSystem.stat(attachmentPath),
992 ).pipe(
993 Effect.tapError((cause) =>
994 Effect.logError("Failed to inspect attachment asset.", {
995 attachmentId: claims.attachmentId,
996 path: attachmentPath,
997 cause,
998 }),
999 ),
1000 Effect.orElseSucceed(() => Option.none()),
1001 );
1002 return Option.isSome(info) && info.value.type === "File"
1003 ? ({
1004 kind: "file",
1005 path: attachmentPath,
1006 ...(claims.download ? { download: true } : {}),
1007 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
1008 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
1009 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
1010 } satisfies ResolvedAsset)
1011 : null;
1012 }
1013
1014 if (claims.kind === "project-favicon") {
1015 if (claims.relativePath === null) return null;
1016 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
1017 workspaceRoot: claims.workspaceRoot,
1018 relativePath: claims.relativePath,
1019 });
1020 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
1021 }
1022
1023 if (claims.kind === "project-favicon-external") {
1024 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
1025 Effect.tapError((cause) =>
1026 Effect.logError("Failed to resolve canonical asset path.", {
1027 filePath: claims.filePath,
1028 cause,
1029 }),
1030 ),
1031 Effect.orElseSucceed(() => null),
1032 );
1033 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
1034 }
1035
1036 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
1037 const { version: _version, ...media } = claims;
1038 return { ...media, kind: "source-control-media" } satisfies ResolvedAsset;
1039 }
1040
1041 if (claims.kind === "tool-output-image") {
1042 const image = yield* readToolOutputImage(claims).pipe(
1043 Effect.tapError((cause) =>
1044 Effect.logError("Failed to read tool output image.", {
1045 threadId: claims.threadId,
1046 itemId: claims.itemId,
1047 cause,
1048 }),
1049 ),
1050 Effect.orElseSucceed(() => null),
1051 );
1052 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
1053 }
1054
1055 if (claims.kind === "environment-theme-background") {
1056 const config = yield* ServerConfig.ServerConfig;
1057 const fileSystem = yield* FileSystem.FileSystem;
1058 // The themes directory may be a symlink; openMediaFile refuses any path that is not canonical.
1059 const themesDir = yield* fileSystem
1060 .realPath(config.environmentThemesDir)
1061 .pipe(Effect.orElseSucceed(() => null));
1062 const background = themesDir === null ? null : findThemeBackground(themesDir, claims.themeId);
1063 if (background === null) return null;
1064 const file = yield* openMediaFile(background.path).pipe(
1065 Effect.tapError((cause) =>
1066 Effect.logError("Failed to open theme background.", { path: background.path, cause }),
1067 ),
1068 Effect.orElseSucceed(() => null),
1069 );
1070 return file ? ({ kind: "file", path: background.path, file } satisfies ResolvedAsset) : null;
1071 }
1072
1073 if (claims.kind === "native-app-icon") {
1074 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
1075 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
1076 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
1077 }
1078
1079 const decodedPath = decodeRelativePath(relativePath);
1080 if (decodedPath === null) return null;
1081 const path = yield* Path.Path;
1082 if (claims.kind === "media-file-exact") {
1083 if (decodedPath !== path.basename(claims.filePath)) return null;
1084 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
1085 Effect.tapError((cause) =>
1086 Effect.logError("Failed to resolve canonical media path.", {
1087 filePath: claims.filePath,
1088 cause,
1089 }),
1090 ),
1091 Effect.orElseSucceed(() => null),
1092 );
1093 if (canonicalFile !== claims.filePath) return null;
1094 const mimeType = claims.download
1095 ? "application/octet-stream"
1096 : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
1097 if (!mimeType) return null;
1098 const file = yield* openMediaFile(canonicalFile, claims).pipe(
1099 Effect.tapError((cause) =>
1100 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
1101 ),
1102 Effect.orElseSucceed(() => null),
1103 );
1104 return file
1105 ? ({
1106 kind: "file",
1107 path: canonicalFile,
1108 mimeType,
1109 file,
1110 ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
1111 } satisfies ResolvedAsset)
1112 : null;
1113 }
1114 if (claims.kind === "workspace-file-exact") {
1115 if (decodedPath !== path.basename(claims.relativePath)) return null;
1116 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1117 workspaceRoot: claims.workspaceRoot,
1118 relativePath: claims.relativePath,
1119 });
1120 // Checked again here: a link can be repointed after its URL was issued.
1121 return exactWorkspaceFile && isWorkspacePreviewEntryPath(exactWorkspaceFile)
1122 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
1123 : null;
1124 }
1125 if (!isPreviewDependencyPath(decodedPath, path)) return null;
1126 const joinedRelativePath =
1127 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1128 if (claims.entryFileName !== undefined) {
1129 // Before the file is resolved and read, so the recorded state is never newer than the response.
1130 const revisions = yield* WorkspacePreviewRevisions.WorkspacePreviewRevisions;
1131 yield* revisions.observe(
1132 {
1133 workspaceRoot: claims.workspaceRoot,
1134 entryRelativePath: path.join(claims.baseRelativePath, claims.entryFileName),
1135 },
1136 joinedRelativePath,
1137 );
1138 }
1139 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1140 workspaceRoot: claims.workspaceRoot,
1141 relativePath: joinedRelativePath,
1142 previewBaseRelativePath: claims.baseRelativePath,
1143 });
1144 return workspaceFile
1145 ? ({ kind: "file", path: workspaceFile, renderIntent: "file-preview" } satisfies ResolvedAsset)
1146 : null;
1147 });