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

AssetAccess.ts

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