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}) {
423 const fileSystem = yield* FileSystem.FileSystem;
424 const path = yield* Path.Path;
425 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
426 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
427 let claims: AssetClaims;
428 let fileName: string;
429 let sourcePath: string | undefined;
430 let imageDimensions: ImageDimensions | null = null;
431
432 switch (input.resource._tag) {
433 case "media-file": {
434 let requestedPath = input.resource.path;
435 if (!path.isAbsolute(requestedPath)) {
436 if (!input.workspaceRoot) {
437 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
438 }
439 const workspaceRoot = yield* workspacePaths
440 .normalizeWorkspaceRoot(input.workspaceRoot)
441 .pipe(
442 Effect.mapError(
443 (cause) =>
444 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
445 ),
446 );
447 requestedPath = path.resolve(workspaceRoot, requestedPath);
448 }
449 const finalized = yield* finalizeAbsoluteMediaFileAsset({
450 requestedPath,
451 resource: input.resource,
452 expiresAt,
453 });
454 claims = finalized.claims;
455 fileName = finalized.fileName;
456 imageDimensions = finalized.imageDimensions;
457 break;
458 }
459 case "workspace-file": {
460 if (!input.workspaceRoot) {
461 return yield* new AssetWorkspaceContextNotFoundError({
462 resource: input.resource,
463 });
464 }
465 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
466 Effect.mapError(
467 (cause) =>
468 new AssetWorkspaceRootNormalizationError({
469 resource: input.resource,
470 cause,
471 }),
472 ),
473 );
474 const finalized = yield* finalizeWorkspaceFileAsset({
475 workspaceRoot,
476 requestedPath: input.resource.path,
477 resource: input.resource,
478 expiresAt,
479 });
480 claims = finalized.claims;
481 fileName = finalized.fileName;
482 imageDimensions = finalized.imageDimensions;
483 break;
484 }
485 case "draft-workspace-file": {
486 // The draft names its workspace root in the resource itself; an explicit
487 // root only overrides it.
488 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
489 if (path.isAbsolute(input.resource.path)) {
490 // An absolute draft path serves exactly like an absolute media path.
491 const finalized = yield* finalizeAbsoluteMediaFileAsset({
492 requestedPath: input.resource.path,
493 resource: input.resource,
494 expiresAt,
495 });
496 claims = finalized.claims;
497 fileName = finalized.fileName;
498 imageDimensions = finalized.imageDimensions;
499 break;
500 }
501 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
502 Effect.mapError(
503 (cause) =>
504 new AssetWorkspaceRootNormalizationError({
505 resource: input.resource,
506 cause,
507 }),
508 ),
509 );
510 const finalized = yield* finalizeWorkspaceFileAsset({
511 workspaceRoot,
512 requestedPath: input.resource.path,
513 resource: input.resource,
514 expiresAt,
515 });
516 claims = finalized.claims;
517 fileName = finalized.fileName;
518 imageDimensions = finalized.imageDimensions;
519 break;
520 }
521 case "attachment": {
522 const config = yield* ServerConfig.ServerConfig;
523 const attachmentPath = resolveAttachmentPathById({
524 attachmentsDir: config.attachmentsDir,
525 attachmentId: input.resource.attachmentId,
526 });
527 if (!attachmentPath) {
528 return yield* new AssetAttachmentNotFoundError({
529 resource: input.resource,
530 });
531 }
532 // Generic files carry their extension inside the attachment id (that
533 // shape resolves the on-disk path); images do not. Videos and images
534 // render inline. Other generic files download unless a viewer requests
535 // a supported document or audio format inline.
536 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
537 const isGenericFile = extension !== null;
538 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
539 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
540 const inlinePreviewMimeType =
541 input.resource.disposition === "inline" && extension !== null
542 ? inlinePreviewMimeTypeForExtension(extension)
543 : undefined;
544 if (!isGenericFile) {
545 imageDimensions = yield* readImageDimensionsFromHeader(attachmentPath);
546 }
547 claims = {
548 version: 1,
549 kind: "attachment",
550 attachmentId: input.resource.attachmentId,
551 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
552 ? { download: true }
553 : {}),
554 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
555 ...(inlinePreviewMimeType !== undefined
556 ? { mimeType: inlinePreviewMimeType }
557 : input.resource.mimeType !== undefined
558 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
559 : {}),
560 expiresAt,
561 };
562 fileName = input.resource.fileName ?? path.basename(attachmentPath);
563 break;
564 }
565 case "project-favicon": {
566 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
567 Effect.mapError(
568 (cause) =>
569 new AssetWorkspaceRootNormalizationError({
570 resource: input.resource,
571 cause,
572 }),
573 ),
574 );
575 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
576 const faviconPath = yield* faviconResolver
577 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
578 .pipe(
579 Effect.mapError(
580 (cause) =>
581 new AssetProjectFaviconResolutionError({
582 resource: input.resource,
583 cause,
584 }),
585 ),
586 );
587 const isExternalOverride =
588 faviconPath !== null &&
589 input.projectFaviconPath !== undefined &&
590 path.isAbsolute(input.projectFaviconPath) &&
591 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
592 const relativePath =
593 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
594 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
595 if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
596 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
597 }
598 sourcePath = sourceFaviconPath ?? undefined;
599 const canonicalFaviconPath = sourceFaviconPath
600 ? yield* (
601 isExternalOverride
602 ? resolveCanonicalFile(sourceFaviconPath)
603 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
604 ).pipe(
605 Effect.mapError(
606 (cause) =>
607 new AssetProjectFaviconInspectionError({
608 resource: input.resource,
609 cause,
610 }),
611 ),
612 )
613 : null;
614 if (sourceFaviconPath && !canonicalFaviconPath) {
615 return yield* new AssetProjectFaviconNotFoundError({
616 resource: input.resource,
617 });
618 }
619 claims =
620 isExternalOverride && canonicalFaviconPath
621 ? {
622 version: 1,
623 kind: "project-favicon-external",
624 filePath: canonicalFaviconPath,
625 expiresAt,
626 }
627 : {
628 version: 1,
629 kind: "project-favicon",
630 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
631 Effect.mapError(
632 (cause) =>
633 new AssetWorkspaceResolutionError({
634 resource: input.resource,
635 cause,
636 }),
637 ),
638 ),
639 relativePath,
640 expiresAt,
641 };
642 if (sourceFaviconPath && canonicalFaviconPath) {
643 const crypto = yield* Crypto.Crypto;
644 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
645 Effect.mapError(
646 (cause) =>
647 new AssetProjectFaviconInspectionError({
648 resource: input.resource,
649 cause,
650 }),
651 ),
652 );
653 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
654 Effect.map(Encoding.encodeHex),
655 Effect.mapError(
656 (cause) =>
657 new AssetProjectFaviconInspectionError({
658 resource: input.resource,
659 cause,
660 }),
661 ),
662 );
663 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
664 } else {
665 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
666 }
667 break;
668 }
669 case "native-app-icon": {
670 claims = {
671 version: 1,
672 kind: "native-app-icon",
673 app: input.resource.app,
674 expiresAt,
675 };
676 fileName = "native-app-icon.png";
677 break;
678 }
679 case "github-media": {
680 const fetchUrl = githubMediaFetchUrl(input.resource.url);
681 if (fetchUrl === null) {
682 return yield* new AssetGitHubMediaUrlValidationError({});
683 }
684 claims = {
685 version: 1,
686 kind: "github-media",
687 url: fetchUrl,
688 cwd: input.resource.cwd,
689 expiresAt,
690 };
691 fileName = githubMediaFileName(fetchUrl);
692 break;
693 }
694 }
695
696 const secretStore = yield* ServerSecretStore.ServerSecretStore;
697 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
698 Effect.mapError(
699 (cause) =>
700 new AssetSigningKeyLoadError({
701 resource: input.resource,
702 cause,
703 }),
704 ),
705 );
706 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
707 const issuedAt = yield* Clock.currentTimeMillis;
708 expiresAt =
709 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
710 PROJECT_FAVICON_TOKEN_BUCKET_MS;
711 claims = { ...claims, expiresAt };
712 }
713 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
714 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
715 return {
716 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
717 expiresAt,
718 ...(sourcePath !== undefined ? { sourcePath } : {}),
719 ...(imageDimensions !== null ? { imageDimensions } : {}),
720 };
721});
722
723export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
724 token: string,
725 relativePath: string,
726) {
727 const [encodedPayload, signature] = token.split(".");
728 if (!encodedPayload || !signature) return null;
729
730 const secretStore = yield* ServerSecretStore.ServerSecretStore;
731 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
732 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
733 Effect.orElseSucceed(() => null),
734 );
735 if (!signingSecret) return null;
736 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
737
738 const claims = decodeClaims(encodedPayload);
739 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
740
741 if (claims.kind === "attachment") {
742 const config = yield* ServerConfig.ServerConfig;
743 const attachmentPath = resolveAttachmentPathById({
744 attachmentsDir: config.attachmentsDir,
745 attachmentId: claims.attachmentId,
746 });
747 if (!attachmentPath) return null;
748 const fileSystem = yield* FileSystem.FileSystem;
749 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
750 Effect.tapError((cause) =>
751 Effect.logError("Failed to inspect attachment asset.", {
752 attachmentId: claims.attachmentId,
753 path: attachmentPath,
754 cause,
755 }),
756 ),
757 Effect.orElseSucceed(() => Option.none()),
758 );
759 return Option.isSome(info) && info.value.type === "File"
760 ? ({
761 kind: "file",
762 path: attachmentPath,
763 ...(claims.download ? { download: true } : {}),
764 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
765 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
766 } satisfies ResolvedAsset)
767 : null;
768 }
769
770 if (claims.kind === "project-favicon") {
771 if (claims.relativePath === null) return null;
772 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
773 workspaceRoot: claims.workspaceRoot,
774 relativePath: claims.relativePath,
775 });
776 return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
777 }
778
779 if (claims.kind === "project-favicon-external") {
780 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
781 Effect.tapError((cause) =>
782 Effect.logError("Failed to resolve canonical asset path.", {
783 filePath: claims.filePath,
784 cause,
785 }),
786 ),
787 Effect.orElseSucceed(() => null),
788 );
789 return faviconPath === claims.filePath
790 ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
791 : null;
792 }
793
794 if (claims.kind === "github-media") {
795 return {
796 kind: "github-media",
797 url: claims.url,
798 cwd: claims.cwd,
799 expiresAt: claims.expiresAt,
800 } satisfies ResolvedAsset;
801 }
802
803 if (claims.kind === "native-app-icon") {
804 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
805 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
806 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
807 }
808
809 const decodedPath = decodeRelativePath(relativePath);
810 if (decodedPath === null) return null;
811 const path = yield* Path.Path;
812 if (claims.kind === "media-file-exact") {
813 if (decodedPath !== path.basename(claims.filePath)) return null;
814 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
815 Effect.tapError((cause) =>
816 Effect.logError("Failed to resolve canonical media path.", {
817 filePath: claims.filePath,
818 cause,
819 }),
820 ),
821 Effect.orElseSucceed(() => null),
822 );
823 if (canonicalFile !== claims.filePath) return null;
824 const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
825 if (!mimeType) return null;
826 const file = yield* openMediaFile(canonicalFile, claims).pipe(
827 Effect.tapError((cause) =>
828 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
829 ),
830 Effect.orElseSucceed(() => null),
831 );
832 return file
833 ? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
834 : null;
835 }
836 if (claims.kind === "workspace-file-exact") {
837 if (decodedPath !== path.basename(claims.relativePath)) return null;
838 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
839 workspaceRoot: claims.workspaceRoot,
840 relativePath: claims.relativePath,
841 });
842 return exactWorkspaceFile
843 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
844 : null;
845 }
846 const segments = decodedPath.split(/[\\/]/);
847 if (
848 decodedPath.length === 0 ||
849 decodedPath.includes("\0") ||
850 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
851 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
852 ) {
853 return null;
854 }
855 const joinedRelativePath =
856 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
857 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
858 workspaceRoot: claims.workspaceRoot,
859 relativePath: joinedRelativePath,
860 });
861 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
862});