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