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