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

AssetAccess.ts

939 lines33.3 KB

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