Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5 AssetGitHubMediaUrlValidationError,
6 AssetPreviewTypeValidationError,
7 AssetProjectFaviconInspectionError,
8 AssetProjectFaviconNotFoundError,
9 AssetProjectFaviconResolutionError,
10 AssetSigningKeyLoadError,
11 AssetWorkspaceAssetInspectionError,
12 AssetWorkspaceAssetNotFoundError,
13 AssetWorkspaceContextNotFoundError,
14 AssetWorkspacePathValidationError,
15 AssetWorkspaceResolutionError,
16 AssetWorkspaceRootNormalizationError,
17 ThreadId,
18 ToolActivityNativeAppReference,
19 TurnItemId,
20} from "@t3tools/contracts";
21import {
22 audioMimeTypeFromExtension,
23 hostPreviewMimeTypeFromExtension,
24 isWorkspaceImagePreviewPath,
25 isWorkspacePreviewEntryPath,
26 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
27 WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
28} from "@t3tools/shared/filePreview";
29import {
30 IMAGE_DIMENSIONS_HEADER_BYTES,
31 readImageDimensions,
32 type ImageDimensions,
33} from "@t3tools/shared/imageDimensions";
34import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";
35import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
36import { toolOutputImages } from "@t3tools/shared/toolOutput";
37import * as Clock from "effect/Clock";
38import * as Crypto from "effect/Crypto";
39import * as Effect from "effect/Effect";
40import * as Hex from "effect/encoding/Hex";
41import * as FileSystem from "effect/FileSystem";
42import * as Option from "effect/Option";
43import * as Path from "effect/Path";
44import * as PlatformError from "effect/PlatformError";
45import * as Schema from "effect/Schema";
46
47import {
48 base64UrlDecodeUtf8,
49 base64UrlEncode,
50 signPayload,
51 timingSafeEqualBase64Url,
52} from "../auth/utils.ts";
53import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
54import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
55import * as ServerConfig from "../config.ts";
56import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
57import { expandHomePathWith } from "../pathExpansion.ts";
58import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
59import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
60import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
61import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
62
63export const ASSET_ROUTE_PREFIX = "/api/assets";
64
65const SIGNING_SECRET_NAME = "asset-access-signing-key";
66const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
67const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
68const PROJECT_FAVICON_VERSION_PREFIX = "v";
69const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
70// Extensions a document viewer or audio player may request inline. The extension comes from
71// the attachment id the server assigned, never from the client's mime type.
72const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
73 pdf: "application/pdf",
74 html: "text/html",
75 htm: "text/html",
76};
77const inlinePreviewMimeTypeForExtension = (extension: string) =>
78 INLINE_PREVIEW_MIME_TYPES[extension] ?? audioMimeTypeFromExtension(`.${extension}`) ?? undefined;
79const PREVIEW_ASSET_EXTENSIONS = new Set([
80 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
81 ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
82 ".css",
83 ".js",
84 ".mjs",
85 ".otf",
86 ".ttf",
87 ".woff",
88 ".woff2",
89]);
90
91const AssetClaimsSchema = Schema.Union([
92 Schema.Struct({
93 version: Schema.Literal(1),
94 kind: Schema.Literal("workspace-file"),
95 workspaceRoot: Schema.String,
96 baseRelativePath: Schema.String,
97 expiresAt: Schema.Number,
98 }),
99 Schema.Struct({
100 version: Schema.Literal(1),
101 kind: Schema.Literal("workspace-file-exact"),
102 workspaceRoot: Schema.String,
103 relativePath: Schema.String,
104 expiresAt: Schema.Number,
105 }),
106 Schema.Struct({
107 version: Schema.Literal(1),
108 kind: Schema.Literal("media-file-exact"),
109 filePath: Schema.String,
110 device: Schema.String,
111 inode: Schema.String,
112 expiresAt: Schema.Number,
113 }),
114 Schema.Struct({
115 version: Schema.Literal(1),
116 kind: Schema.Literal("attachment"),
117 attachmentId: Schema.String,
118 /** Decided at mint time. Absent tokens (from before this field) serve
119 inline, which is only ever the image case. */
120 download: Schema.optionalKey(Schema.Boolean),
121 /** Display name and mime the caller supplied at mint time; drive the
122 download filename and Content-Type. */
123 fileName: Schema.optionalKey(Schema.String),
124 mimeType: Schema.optionalKey(Schema.String),
125 expiresAt: Schema.Number,
126 }),
127 Schema.Struct({
128 version: Schema.Literal(1),
129 kind: Schema.Literal("project-favicon"),
130 workspaceRoot: Schema.String,
131 relativePath: Schema.NullOr(Schema.String),
132 expiresAt: Schema.Number,
133 }),
134 Schema.Struct({
135 version: Schema.Literal(1),
136 kind: Schema.Literal("project-favicon-external"),
137 filePath: Schema.String,
138 expiresAt: Schema.Number,
139 }),
140 Schema.Struct({
141 version: Schema.Literal(1),
142 kind: Schema.Literal("native-app-icon"),
143 app: ToolActivityNativeAppReference,
144 expiresAt: Schema.Number,
145 }),
146 Schema.Struct({
147 version: Schema.Literal(1),
148 kind: Schema.Literal("tool-output-image"),
149 threadId: ThreadId,
150 itemId: TurnItemId,
151 index: Schema.Number,
152 expiresAt: Schema.Number,
153 }),
154 Schema.Struct({
155 version: Schema.Literal(1),
156 kind: Schema.Literal("github-media"),
157 /** Already narrowed to a GitHub media host at mint time; the signature is what keeps it there. */
158 url: Schema.String,
159 cwd: Schema.String,
160 expiresAt: Schema.Number,
161 }),
162]);
163type AssetClaims = typeof AssetClaimsSchema.Type;
164
165const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
166const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
167const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
168
169export type ResolvedAsset =
170 | {
171 readonly kind: "file";
172 readonly path: string;
173 readonly download?: boolean;
174 readonly fileName?: string;
175 readonly mimeType?: string;
176 readonly file?: OpenMediaFile;
177 }
178 | {
179 readonly kind: "bytes";
180 readonly bytes: Uint8Array;
181 readonly mimeType: string;
182 }
183 | {
184 readonly kind: "github-media";
185 readonly url: string;
186 readonly cwd: string;
187 /** When the signed URL that granted this stops working, which bounds how long a client
188 may keep the bytes it fetched with it. */
189 readonly expiresAt: number;
190 };
191
192function decodeClaims(encodedPayload: string): AssetClaims | null {
193 try {
194 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
195 } catch {
196 return null;
197 }
198}
199
200function decodeRelativePath(value: string): string | null {
201 try {
202 return decodeURIComponent(value);
203 } catch {
204 return null;
205 }
206}
207
208const optionOnNotFound = <A, R>(
209 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
210): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
211 effect.pipe(
212 Effect.asSome,
213 Effect.catchTags({
214 PlatformError: (error) =>
215 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
216 }),
217 );
218
219// The largest image a provider turn accepts, as base64 (4 characters per 3 bytes).
220const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH = Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
221
222/**
223 * Decodes one image a tool returned inline; null when the stored item has no
224 * such image, or it is larger than a provider turn accepts.
225 */
226const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
227 readonly threadId: ThreadId;
228 readonly itemId: TurnItemId;
229 readonly index: number;
230}) {
231 const orchestrator = yield* Orchestrator.OrchestratorV2;
232 const item = yield* orchestrator.getTurnItem(input);
233 const image =
234 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
235 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
236 ? null
237 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
238});
239
240const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
241 filePath: string,
242) {
243 const fileSystem = yield* FileSystem.FileSystem;
244 const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
245 if (Option.isNone(canonicalFile)) return null;
246
247 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
248 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
249});
250
251const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
252 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
253 const fileSystem = yield* FileSystem.FileSystem;
254 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
255 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
256 Effect.asSome,
257 Effect.catchTags({
258 WorkspacePathOutsideRootError: () => Effect.succeedNone,
259 }),
260 );
261 if (Option.isNone(resolved)) return null;
262
263 const [canonicalRoot, canonicalFile] = yield* Effect.all([
264 optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
265 optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
266 ]);
267 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
268
269 const path = yield* Path.Path;
270 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
271 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
272
273 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
274 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
275 },
276);
277
278const resolveCanonicalWorkspaceFileForRequest = (input: {
279 readonly workspaceRoot: string;
280 readonly relativePath: string;
281}) =>
282 resolveCanonicalWorkspaceFile(input).pipe(
283 Effect.tapError((cause) =>
284 Effect.logError("Failed to resolve canonical asset path.", {
285 workspaceRoot: input.workspaceRoot,
286 relativePath: input.relativePath,
287 cause,
288 }),
289 ),
290 Effect.orElseSucceed(() => null),
291 );
292
293/**
294 * Reads pixel dimensions from an image's header so clients can reserve the
295 * exact box before the bytes arrive. Best effort: an unreadable or unsupported
296 * file just leaves the field out, and the client measures after decode. Only
297 * formats the parser understands are opened; SVG and the rest are skipped.
298 */
299const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
300
301/** From the identity-checked, non-blocking handle the caller already holds. */
302const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
303 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
304 Effect.map(readImageDimensions),
305 Effect.orElseSucceed((): ImageDimensions | null => null),
306 );
307
308/**
309 * Opens through `openMediaFile` so a path swapped for a FIFO cannot block the
310 * request; a regular open would wait for a writer that never comes.
311 */
312const readImageDimensionsFromHeader = (filePath: string) =>
313 openMediaFile(filePath).pipe(
314 Effect.flatMap((file) =>
315 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
316 ),
317 Effect.scoped,
318 Effect.orElseSucceed((): ImageDimensions | null => null),
319 );
320
321const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
322 function* (input: {
323 readonly requestedPath: string;
324 readonly resource: AssetResource;
325 readonly expiresAt: number;
326 }) {
327 const path = yield* Path.Path;
328 const canonicalFile = yield* resolveCanonicalFile(input.requestedPath).pipe(
329 Effect.mapError(
330 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
331 ),
332 );
333 if (!canonicalFile) {
334 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
335 }
336 if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
337 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
338 }
339 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
340 const opened = yield* openMediaFile(canonicalFile).pipe(
341 Effect.flatMap((file) =>
342 file === null
343 ? Effect.succeed(null)
344 : Effect.map(
345 wantsDimensions
346 ? readImageDimensionsFromOpenFile(canonicalFile, file)
347 : Effect.succeed(null),
348 (dimensions) => ({
349 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
350 dimensions,
351 }),
352 ),
353 ),
354 Effect.scoped,
355 Effect.mapError(
356 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
357 ),
358 );
359 if (!opened) {
360 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
361 }
362 return {
363 claims: {
364 version: 1 as const,
365 kind: "media-file-exact" as const,
366 filePath: canonicalFile,
367 ...opened.identity,
368 expiresAt: input.expiresAt,
369 },
370 fileName: path.basename(canonicalFile),
371 imageDimensions: opened.dimensions,
372 };
373 },
374);
375
376const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
377 function* (input: {
378 readonly workspaceRoot: string;
379 readonly requestedPath: string;
380 readonly resource: AssetResource;
381 readonly expiresAt: number;
382 }) {
383 const path = yield* Path.Path;
384 const fileSystem = yield* FileSystem.FileSystem;
385 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
386 const relativePath = path.isAbsolute(input.requestedPath)
387 ? path.relative(input.workspaceRoot, input.requestedPath)
388 : input.requestedPath;
389 const resolved = yield* workspacePaths
390 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
391 .pipe(
392 Effect.mapError(
393 (cause) =>
394 new AssetWorkspacePathValidationError({
395 resource: input.resource,
396 cause,
397 }),
398 ),
399 );
400 if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
401 return yield* new AssetPreviewTypeValidationError({
402 resource: input.resource,
403 });
404 }
405 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
406 workspaceRoot: input.workspaceRoot,
407 relativePath: resolved.relativePath,
408 }).pipe(
409 Effect.mapError(
410 (cause) =>
411 new AssetWorkspaceAssetInspectionError({
412 resource: input.resource,
413 cause,
414 }),
415 ),
416 );
417 if (!canonicalFile) {
418 return yield* new AssetWorkspaceAssetNotFoundError({
419 resource: input.resource,
420 });
421 }
422 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
423 Effect.mapError(
424 (cause) =>
425 new AssetWorkspaceResolutionError({
426 resource: input.resource,
427 cause,
428 }),
429 ),
430 );
431 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
432 path.extname(resolved.relativePath).toLowerCase(),
433 )
434 ? yield* readImageDimensionsFromHeader(canonicalFile)
435 : null;
436 return {
437 claims: isWorkspaceImagePreviewPath(resolved.relativePath)
438 ? {
439 version: 1 as const,
440 kind: "workspace-file-exact" as const,
441 workspaceRoot: canonicalWorkspaceRoot,
442 relativePath: resolved.relativePath,
443 expiresAt: input.expiresAt,
444 }
445 : {
446 version: 1 as const,
447 kind: "workspace-file" as const,
448 workspaceRoot: canonicalWorkspaceRoot,
449 baseRelativePath: path.dirname(resolved.relativePath),
450 expiresAt: input.expiresAt,
451 },
452 fileName: path.basename(resolved.relativePath),
453 imageDimensions,
454 };
455 },
456);
457
458export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
459 readonly resource: AssetResource;
460 readonly workspaceRoot?: string;
461 readonly projectFaviconPath?: string;
462 /** The project's clone has not landed, so its icon is reported missing without a lookup. */
463 readonly projectCheckoutPending?: boolean;
464}) {
465 const fileSystem = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
468 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
469 let claims: AssetClaims;
470 let fileName: string;
471 let sourcePath: string | undefined;
472 let imageDimensions: ImageDimensions | null = null;
473
474 switch (input.resource._tag) {
475 case "media-file": {
476 let requestedPath = expandHomePathWith(input.resource.path, path);
477 if (!path.isAbsolute(requestedPath)) {
478 if (!input.workspaceRoot) {
479 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
480 }
481 const workspaceRoot = yield* workspacePaths
482 .normalizeWorkspaceRoot(input.workspaceRoot)
483 .pipe(
484 Effect.mapError(
485 (cause) =>
486 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
487 ),
488 );
489 requestedPath = path.resolve(workspaceRoot, requestedPath);
490 }
491 const finalized = yield* finalizeAbsoluteMediaFileAsset({
492 requestedPath,
493 resource: input.resource,
494 expiresAt,
495 });
496 claims = finalized.claims;
497 fileName = finalized.fileName;
498 imageDimensions = finalized.imageDimensions;
499 break;
500 }
501 case "workspace-file": {
502 if (!input.workspaceRoot) {
503 return yield* new AssetWorkspaceContextNotFoundError({
504 resource: input.resource,
505 });
506 }
507 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
508 Effect.mapError(
509 (cause) =>
510 new AssetWorkspaceRootNormalizationError({
511 resource: input.resource,
512 cause,
513 }),
514 ),
515 );
516 const finalized = yield* finalizeWorkspaceFileAsset({
517 workspaceRoot,
518 requestedPath: input.resource.path,
519 resource: input.resource,
520 expiresAt,
521 });
522 claims = finalized.claims;
523 fileName = finalized.fileName;
524 imageDimensions = finalized.imageDimensions;
525 break;
526 }
527 case "draft-workspace-file": {
528 // The draft names its workspace root in the resource itself; an explicit
529 // root only overrides it.
530 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
531 if (path.isAbsolute(input.resource.path)) {
532 // An absolute draft path serves exactly like an absolute media path.
533 const finalized = yield* finalizeAbsoluteMediaFileAsset({
534 requestedPath: input.resource.path,
535 resource: input.resource,
536 expiresAt,
537 });
538 claims = finalized.claims;
539 fileName = finalized.fileName;
540 imageDimensions = finalized.imageDimensions;
541 break;
542 }
543 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
544 Effect.mapError(
545 (cause) =>
546 new AssetWorkspaceRootNormalizationError({
547 resource: input.resource,
548 cause,
549 }),
550 ),
551 );
552 const finalized = yield* finalizeWorkspaceFileAsset({
553 workspaceRoot,
554 requestedPath: input.resource.path,
555 resource: input.resource,
556 expiresAt,
557 });
558 claims = finalized.claims;
559 fileName = finalized.fileName;
560 imageDimensions = finalized.imageDimensions;
561 break;
562 }
563 case "attachment": {
564 const config = yield* ServerConfig.ServerConfig;
565 const attachmentPath = resolveAttachmentPathById({
566 attachmentsDir: config.attachmentsDir,
567 attachmentId: input.resource.attachmentId,
568 });
569 if (!attachmentPath) {
570 return yield* new AssetAttachmentNotFoundError({
571 resource: input.resource,
572 });
573 }
574 // Generic files carry their extension inside the attachment id (that
575 // shape resolves the on-disk path); images do not. Videos and images
576 // render inline. Other generic files download unless a viewer requests
577 // a supported document or audio format inline.
578 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
579 const isGenericFile = extension !== null;
580 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
581 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
582 const inlinePreviewMimeType =
583 input.resource.disposition === "inline" && extension !== null
584 ? inlinePreviewMimeTypeForExtension(extension)
585 : undefined;
586 if (!isGenericFile) {
587 imageDimensions = yield* readImageDimensionsFromHeader(attachmentPath);
588 }
589 claims = {
590 version: 1,
591 kind: "attachment",
592 attachmentId: input.resource.attachmentId,
593 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
594 ? { download: true }
595 : {}),
596 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
597 ...(inlinePreviewMimeType !== undefined
598 ? { mimeType: inlinePreviewMimeType }
599 : input.resource.mimeType !== undefined
600 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
601 : {}),
602 expiresAt,
603 };
604 fileName = input.resource.fileName ?? path.basename(attachmentPath);
605 break;
606 }
607 case "project-favicon": {
608 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
609 Effect.mapError(
610 (cause) =>
611 new AssetWorkspaceRootNormalizationError({
612 resource: input.resource,
613 cause,
614 }),
615 ),
616 );
617 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
618 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
619 const faviconPath = input.projectCheckoutPending
620 ? null
621 : yield* faviconResolver
622 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
623 .pipe(
624 Effect.mapError(
625 (cause) =>
626 new AssetProjectFaviconResolutionError({
627 resource: input.resource,
628 cause,
629 }),
630 ),
631 );
632 const isExternalOverride =
633 faviconPath !== null &&
634 input.projectFaviconPath !== undefined &&
635 path.isAbsolute(input.projectFaviconPath) &&
636 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
637 const relativePath =
638 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
639 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
640 if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
641 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
642 }
643 sourcePath = sourceFaviconPath ?? undefined;
644 const canonicalFaviconPath = sourceFaviconPath
645 ? yield* (
646 isExternalOverride
647 ? resolveCanonicalFile(sourceFaviconPath)
648 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
649 ).pipe(
650 Effect.mapError(
651 (cause) =>
652 new AssetProjectFaviconInspectionError({
653 resource: input.resource,
654 cause,
655 }),
656 ),
657 )
658 : null;
659 if (sourceFaviconPath && !canonicalFaviconPath) {
660 return yield* new AssetProjectFaviconNotFoundError({
661 resource: input.resource,
662 });
663 }
664 claims =
665 isExternalOverride && canonicalFaviconPath
666 ? {
667 version: 1,
668 kind: "project-favicon-external",
669 filePath: canonicalFaviconPath,
670 expiresAt,
671 }
672 : {
673 version: 1,
674 kind: "project-favicon",
675 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
676 Effect.mapError(
677 (cause) =>
678 new AssetWorkspaceResolutionError({
679 resource: input.resource,
680 cause,
681 }),
682 ),
683 ),
684 relativePath,
685 expiresAt,
686 };
687 if (sourceFaviconPath && canonicalFaviconPath) {
688 const crypto = yield* Crypto.Crypto;
689 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
690 Effect.mapError(
691 (cause) =>
692 new AssetProjectFaviconInspectionError({
693 resource: input.resource,
694 cause,
695 }),
696 ),
697 );
698 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
699 Effect.map(Hex.encode),
700 Effect.mapError(
701 (cause) =>
702 new AssetProjectFaviconInspectionError({
703 resource: input.resource,
704 cause,
705 }),
706 ),
707 );
708 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
709 } else {
710 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
711 }
712 break;
713 }
714 case "tool-output-image": {
715 const image = yield* readToolOutputImage(input.resource).pipe(
716 Effect.mapError(
717 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
718 ),
719 );
720 if (image === null) {
721 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
722 }
723 claims = {
724 version: 1,
725 kind: "tool-output-image",
726 threadId: input.resource.threadId,
727 itemId: input.resource.itemId,
728 index: input.resource.index,
729 expiresAt,
730 };
731 // The allowed types are all `image/<extension>`.
732 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
733 imageDimensions = readImageDimensions(image.bytes);
734 break;
735 }
736 case "native-app-icon": {
737 claims = {
738 version: 1,
739 kind: "native-app-icon",
740 app: input.resource.app,
741 expiresAt,
742 };
743 fileName = "native-app-icon.png";
744 break;
745 }
746 case "github-media": {
747 const fetchUrl = githubMediaFetchUrl(input.resource.url);
748 if (fetchUrl === null) {
749 return yield* new AssetGitHubMediaUrlValidationError({});
750 }
751 claims = {
752 version: 1,
753 kind: "github-media",
754 url: fetchUrl,
755 cwd: input.resource.cwd,
756 expiresAt,
757 };
758 fileName = githubMediaFileName(fetchUrl);
759 break;
760 }
761 }
762
763 const secretStore = yield* ServerSecretStore.ServerSecretStore;
764 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
765 Effect.mapError(
766 (cause) =>
767 new AssetSigningKeyLoadError({
768 resource: input.resource,
769 cause,
770 }),
771 ),
772 );
773 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
774 const issuedAt = yield* Clock.currentTimeMillis;
775 expiresAt =
776 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
777 PROJECT_FAVICON_TOKEN_BUCKET_MS;
778 claims = { ...claims, expiresAt };
779 }
780 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
781 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
782 return {
783 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
784 expiresAt,
785 ...(sourcePath !== undefined ? { sourcePath } : {}),
786 ...(imageDimensions !== null ? { imageDimensions } : {}),
787 };
788});
789
790export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
791 token: string,
792 relativePath: string,
793) {
794 const [encodedPayload, signature] = token.split(".");
795 if (!encodedPayload || !signature) return null;
796
797 const secretStore = yield* ServerSecretStore.ServerSecretStore;
798 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
799 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
800 Effect.orElseSucceed(() => null),
801 );
802 if (!signingSecret) return null;
803 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
804
805 const claims = decodeClaims(encodedPayload);
806 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
807
808 if (claims.kind === "attachment") {
809 const config = yield* ServerConfig.ServerConfig;
810 const attachmentPath = resolveAttachmentPathById({
811 attachmentsDir: config.attachmentsDir,
812 attachmentId: claims.attachmentId,
813 });
814 if (!attachmentPath) return null;
815 const fileSystem = yield* FileSystem.FileSystem;
816 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
817 Effect.tapError((cause) =>
818 Effect.logError("Failed to inspect attachment asset.", {
819 attachmentId: claims.attachmentId,
820 path: attachmentPath,
821 cause,
822 }),
823 ),
824 Effect.orElseSucceed(() => Option.none()),
825 );
826 return Option.isSome(info) && info.value.type === "File"
827 ? ({
828 kind: "file",
829 path: attachmentPath,
830 ...(claims.download ? { download: true } : {}),
831 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
832 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
833 } satisfies ResolvedAsset)
834 : null;
835 }
836
837 if (claims.kind === "project-favicon") {
838 if (claims.relativePath === null) return null;
839 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
840 workspaceRoot: claims.workspaceRoot,
841 relativePath: claims.relativePath,
842 });
843 return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
844 }
845
846 if (claims.kind === "project-favicon-external") {
847 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
848 Effect.tapError((cause) =>
849 Effect.logError("Failed to resolve canonical asset path.", {
850 filePath: claims.filePath,
851 cause,
852 }),
853 ),
854 Effect.orElseSucceed(() => null),
855 );
856 return faviconPath === claims.filePath
857 ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
858 : null;
859 }
860
861 if (claims.kind === "github-media") {
862 return {
863 kind: "github-media",
864 url: claims.url,
865 cwd: claims.cwd,
866 expiresAt: claims.expiresAt,
867 } satisfies ResolvedAsset;
868 }
869
870 if (claims.kind === "tool-output-image") {
871 const image = yield* readToolOutputImage(claims).pipe(
872 Effect.tapError((cause) =>
873 Effect.logError("Failed to read tool output image.", {
874 threadId: claims.threadId,
875 itemId: claims.itemId,
876 cause,
877 }),
878 ),
879 Effect.orElseSucceed(() => null),
880 );
881 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
882 }
883
884 if (claims.kind === "native-app-icon") {
885 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
886 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
887 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
888 }
889
890 const decodedPath = decodeRelativePath(relativePath);
891 if (decodedPath === null) return null;
892 const path = yield* Path.Path;
893 if (claims.kind === "media-file-exact") {
894 if (decodedPath !== path.basename(claims.filePath)) return null;
895 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
896 Effect.tapError((cause) =>
897 Effect.logError("Failed to resolve canonical media path.", {
898 filePath: claims.filePath,
899 cause,
900 }),
901 ),
902 Effect.orElseSucceed(() => null),
903 );
904 if (canonicalFile !== claims.filePath) return null;
905 const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
906 if (!mimeType) return null;
907 const file = yield* openMediaFile(canonicalFile, claims).pipe(
908 Effect.tapError((cause) =>
909 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
910 ),
911 Effect.orElseSucceed(() => null),
912 );
913 return file
914 ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
915 : null;
916 }
917 if (claims.kind === "workspace-file-exact") {
918 if (decodedPath !== path.basename(claims.relativePath)) return null;
919 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
920 workspaceRoot: claims.workspaceRoot,
921 relativePath: claims.relativePath,
922 });
923 return exactWorkspaceFile
924 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
925 : null;
926 }
927 const segments = decodedPath.split(/[\\/]/);
928 if (
929 decodedPath.length === 0 ||
930 decodedPath.includes("\0") ||
931 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
932 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
933 ) {
934 return null;
935 }
936 const joinedRelativePath =
937 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
938 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
939 workspaceRoot: claims.workspaceRoot,
940 relativePath: joinedRelativePath,
941 });
942 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
943});