Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 AssetPreviewTypeValidationError,
5 AssetProjectFaviconInspectionError,
6 AssetProjectFaviconNotFoundError,
7 AssetProjectFaviconResolutionError,
8 AssetSigningKeyLoadError,
9 AssetWorkspaceAssetInspectionError,
10 AssetWorkspaceAssetNotFoundError,
11 AssetWorkspaceContextNotFoundError,
12 AssetWorkspacePathValidationError,
13 AssetWorkspaceResolutionError,
14 AssetWorkspaceRootNormalizationError,
15} from "@t3tools/contracts";
16import {
17 isWorkspaceImagePreviewPath,
18 isWorkspacePreviewEntryPath,
19 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
20 WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
21} from "@t3tools/shared/filePreview";
22import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
23import * as Clock from "effect/Clock";
24import * as Crypto from "effect/Crypto";
25import * as Effect from "effect/Effect";
26import * as Encoding from "effect/Encoding";
27import * as FileSystem from "effect/FileSystem";
28import * as Option from "effect/Option";
29import * as Path from "effect/Path";
30import * as PlatformError from "effect/PlatformError";
31import * as Schema from "effect/Schema";
32
33import {
34 base64UrlDecodeUtf8,
35 base64UrlEncode,
36 signPayload,
37 timingSafeEqualBase64Url,
38} from "../auth/utils.ts";
39import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
40import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
41import * as ServerConfig from "../config.ts";
42import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
43import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
44
45export const ASSET_ROUTE_PREFIX = "/api/assets";
46
47const SIGNING_SECRET_NAME = "asset-access-signing-key";
48const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
49const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
50const PROJECT_FAVICON_VERSION_PREFIX = "v";
51const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
52const PREVIEW_ASSET_EXTENSIONS = new Set([
53 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
54 ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
55 ".css",
56 ".js",
57 ".mjs",
58 ".otf",
59 ".ttf",
60 ".woff",
61 ".woff2",
62]);
63
64const AssetClaimsSchema = Schema.Union([
65 Schema.Struct({
66 version: Schema.Literal(1),
67 kind: Schema.Literal("workspace-file"),
68 workspaceRoot: Schema.String,
69 baseRelativePath: Schema.String,
70 expiresAt: Schema.Number,
71 }),
72 Schema.Struct({
73 version: Schema.Literal(1),
74 kind: Schema.Literal("workspace-file-exact"),
75 workspaceRoot: Schema.String,
76 relativePath: Schema.String,
77 expiresAt: Schema.Number,
78 }),
79 Schema.Struct({
80 version: Schema.Literal(1),
81 kind: Schema.Literal("attachment"),
82 attachmentId: Schema.String,
83 /** Decided at mint time. Absent tokens (from before this field) serve
84 inline, which is only ever the image case. */
85 download: Schema.optionalKey(Schema.Boolean),
86 /** Display name and mime the caller supplied at mint time; drive the
87 download filename and Content-Type. */
88 fileName: Schema.optionalKey(Schema.String),
89 mimeType: Schema.optionalKey(Schema.String),
90 expiresAt: Schema.Number,
91 }),
92 Schema.Struct({
93 version: Schema.Literal(1),
94 kind: Schema.Literal("project-favicon"),
95 workspaceRoot: Schema.String,
96 relativePath: Schema.NullOr(Schema.String),
97 expiresAt: Schema.Number,
98 }),
99 Schema.Struct({
100 version: Schema.Literal(1),
101 kind: Schema.Literal("project-favicon-external"),
102 filePath: Schema.String,
103 expiresAt: Schema.Number,
104 }),
105]);
106type AssetClaims = typeof AssetClaimsSchema.Type;
107
108const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
109const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
110const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
111
112export type ResolvedAsset = {
113 readonly kind: "file";
114 readonly path: string;
115 readonly download?: boolean;
116 readonly fileName?: string;
117 readonly mimeType?: string;
118};
119
120function decodeClaims(encodedPayload: string): AssetClaims | null {
121 try {
122 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
123 } catch {
124 return null;
125 }
126}
127
128function decodeRelativePath(value: string): string | null {
129 try {
130 return decodeURIComponent(value);
131 } catch {
132 return null;
133 }
134}
135
136const optionOnNotFound = <A, R>(
137 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
138): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
139 effect.pipe(
140 Effect.map(Option.some),
141 Effect.catchTags({
142 PlatformError: (error) =>
143 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
144 }),
145 );
146
147const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
148 filePath: string,
149) {
150 const fileSystem = yield* FileSystem.FileSystem;
151 const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
152 if (Option.isNone(canonicalFile)) return null;
153
154 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
155 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
156});
157
158const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
159 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
160 const fileSystem = yield* FileSystem.FileSystem;
161 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
162 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
163 Effect.map(Option.some),
164 Effect.catchTags({
165 WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
166 }),
167 );
168 if (Option.isNone(resolved)) return null;
169
170 const [canonicalRoot, canonicalFile] = yield* Effect.all([
171 optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
172 optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
173 ]);
174 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
175
176 const path = yield* Path.Path;
177 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
178 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
179
180 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
181 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
182 },
183);
184
185const resolveCanonicalWorkspaceFileForRequest = (input: {
186 readonly workspaceRoot: string;
187 readonly relativePath: string;
188}) =>
189 resolveCanonicalWorkspaceFile(input).pipe(
190 Effect.tapError((cause) =>
191 Effect.logError("Failed to resolve canonical asset path.", {
192 workspaceRoot: input.workspaceRoot,
193 relativePath: input.relativePath,
194 cause,
195 }),
196 ),
197 Effect.orElseSucceed(() => null),
198 );
199
200export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
201 readonly resource: AssetResource;
202 readonly workspaceRoot?: string;
203 readonly projectFaviconPath?: string;
204}) {
205 const fileSystem = yield* FileSystem.FileSystem;
206 const path = yield* Path.Path;
207 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
208 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
209 let claims: AssetClaims;
210 let fileName: string;
211 let sourcePath: string | undefined;
212
213 switch (input.resource._tag) {
214 case "workspace-file": {
215 if (!input.workspaceRoot) {
216 return yield* new AssetWorkspaceContextNotFoundError({
217 resource: input.resource,
218 });
219 }
220 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
221 Effect.mapError(
222 (cause) =>
223 new AssetWorkspaceRootNormalizationError({
224 resource: input.resource,
225 cause,
226 }),
227 ),
228 );
229 const relativePath = path.isAbsolute(input.resource.path)
230 ? path.relative(workspaceRoot, input.resource.path)
231 : input.resource.path;
232 const resolved = yield* workspacePaths
233 .resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
234 .pipe(
235 Effect.mapError(
236 (cause) =>
237 new AssetWorkspacePathValidationError({
238 resource: input.resource,
239 cause,
240 }),
241 ),
242 );
243 if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
244 return yield* new AssetPreviewTypeValidationError({
245 resource: input.resource,
246 });
247 }
248 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
249 workspaceRoot,
250 relativePath: resolved.relativePath,
251 }).pipe(
252 Effect.mapError(
253 (cause) =>
254 new AssetWorkspaceAssetInspectionError({
255 resource: input.resource,
256 cause,
257 }),
258 ),
259 );
260 if (!canonicalFile) {
261 return yield* new AssetWorkspaceAssetNotFoundError({
262 resource: input.resource,
263 });
264 }
265 const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
266 Effect.mapError(
267 (cause) =>
268 new AssetWorkspaceResolutionError({
269 resource: input.resource,
270 cause,
271 }),
272 ),
273 );
274 claims = isWorkspaceImagePreviewPath(resolved.relativePath)
275 ? {
276 version: 1,
277 kind: "workspace-file-exact",
278 workspaceRoot: canonicalWorkspaceRoot,
279 relativePath: resolved.relativePath,
280 expiresAt,
281 }
282 : {
283 version: 1,
284 kind: "workspace-file",
285 workspaceRoot: canonicalWorkspaceRoot,
286 baseRelativePath: path.dirname(resolved.relativePath),
287 expiresAt,
288 };
289 fileName = path.basename(resolved.relativePath);
290 break;
291 }
292 case "attachment": {
293 const config = yield* ServerConfig.ServerConfig;
294 const attachmentPath = resolveAttachmentPathById({
295 attachmentsDir: config.attachmentsDir,
296 attachmentId: input.resource.attachmentId,
297 });
298 if (!attachmentPath) {
299 return yield* new AssetAttachmentNotFoundError({
300 resource: input.resource,
301 });
302 }
303 // Generic files carry their extension inside the attachment id (that
304 // shape resolves the on-disk path); images do not. Videos and images
305 // render inline; other generic files download.
306 const isGenericFile = parseAttachmentFileExtension(input.resource.attachmentId) !== null;
307 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
308 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
309 claims = {
310 version: 1,
311 kind: "attachment",
312 attachmentId: input.resource.attachmentId,
313 ...(isGenericFile && !isVideo ? { download: true } : {}),
314 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
315 ...(input.resource.mimeType !== undefined
316 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
317 : {}),
318 expiresAt,
319 };
320 fileName = input.resource.fileName ?? path.basename(attachmentPath);
321 break;
322 }
323 case "project-favicon": {
324 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
325 Effect.mapError(
326 (cause) =>
327 new AssetWorkspaceRootNormalizationError({
328 resource: input.resource,
329 cause,
330 }),
331 ),
332 );
333 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
334 const faviconPath = yield* faviconResolver
335 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
336 .pipe(
337 Effect.mapError(
338 (cause) =>
339 new AssetProjectFaviconResolutionError({
340 resource: input.resource,
341 cause,
342 }),
343 ),
344 );
345 const isExternalOverride =
346 faviconPath !== null &&
347 input.projectFaviconPath !== undefined &&
348 path.isAbsolute(input.projectFaviconPath) &&
349 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
350 const relativePath =
351 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
352 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
353 if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
354 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
355 }
356 sourcePath = sourceFaviconPath ?? undefined;
357 const canonicalFaviconPath = sourceFaviconPath
358 ? yield* (
359 isExternalOverride
360 ? resolveCanonicalFile(sourceFaviconPath)
361 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
362 ).pipe(
363 Effect.mapError(
364 (cause) =>
365 new AssetProjectFaviconInspectionError({
366 resource: input.resource,
367 cause,
368 }),
369 ),
370 )
371 : null;
372 if (sourceFaviconPath && !canonicalFaviconPath) {
373 return yield* new AssetProjectFaviconNotFoundError({
374 resource: input.resource,
375 });
376 }
377 claims =
378 isExternalOverride && canonicalFaviconPath
379 ? {
380 version: 1,
381 kind: "project-favicon-external",
382 filePath: canonicalFaviconPath,
383 expiresAt,
384 }
385 : {
386 version: 1,
387 kind: "project-favicon",
388 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
389 Effect.mapError(
390 (cause) =>
391 new AssetWorkspaceResolutionError({
392 resource: input.resource,
393 cause,
394 }),
395 ),
396 ),
397 relativePath,
398 expiresAt,
399 };
400 if (sourceFaviconPath && canonicalFaviconPath) {
401 const crypto = yield* Crypto.Crypto;
402 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
403 Effect.mapError(
404 (cause) =>
405 new AssetProjectFaviconInspectionError({
406 resource: input.resource,
407 cause,
408 }),
409 ),
410 );
411 const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
412 Effect.map(Encoding.encodeHex),
413 Effect.mapError(
414 (cause) =>
415 new AssetProjectFaviconInspectionError({
416 resource: input.resource,
417 cause,
418 }),
419 ),
420 );
421 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
422 } else {
423 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
424 }
425 break;
426 }
427 }
428
429 const secretStore = yield* ServerSecretStore.ServerSecretStore;
430 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
431 Effect.mapError(
432 (cause) =>
433 new AssetSigningKeyLoadError({
434 resource: input.resource,
435 cause,
436 }),
437 ),
438 );
439 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
440 const issuedAt = yield* Clock.currentTimeMillis;
441 expiresAt =
442 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
443 PROJECT_FAVICON_TOKEN_BUCKET_MS;
444 claims = { ...claims, expiresAt };
445 }
446 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
447 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
448 return {
449 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
450 expiresAt,
451 ...(sourcePath !== undefined ? { sourcePath } : {}),
452 };
453});
454
455export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
456 token: string,
457 relativePath: string,
458) {
459 const [encodedPayload, signature] = token.split(".");
460 if (!encodedPayload || !signature) return null;
461
462 const secretStore = yield* ServerSecretStore.ServerSecretStore;
463 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
464 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
465 Effect.orElseSucceed(() => null),
466 );
467 if (!signingSecret) return null;
468 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
469
470 const claims = decodeClaims(encodedPayload);
471 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
472
473 if (claims.kind === "attachment") {
474 const config = yield* ServerConfig.ServerConfig;
475 const attachmentPath = resolveAttachmentPathById({
476 attachmentsDir: config.attachmentsDir,
477 attachmentId: claims.attachmentId,
478 });
479 if (!attachmentPath) return null;
480 const fileSystem = yield* FileSystem.FileSystem;
481 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
482 Effect.tapError((cause) =>
483 Effect.logError("Failed to inspect attachment asset.", {
484 attachmentId: claims.attachmentId,
485 path: attachmentPath,
486 cause,
487 }),
488 ),
489 Effect.orElseSucceed(() => Option.none()),
490 );
491 return Option.isSome(info) && info.value.type === "File"
492 ? ({
493 kind: "file",
494 path: attachmentPath,
495 ...(claims.download ? { download: true } : {}),
496 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
497 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
498 } satisfies ResolvedAsset)
499 : null;
500 }
501
502 if (claims.kind === "project-favicon") {
503 if (claims.relativePath === null) return null;
504 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
505 workspaceRoot: claims.workspaceRoot,
506 relativePath: claims.relativePath,
507 });
508 return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
509 }
510
511 if (claims.kind === "project-favicon-external") {
512 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
513 Effect.tapError((cause) =>
514 Effect.logError("Failed to resolve canonical asset path.", {
515 filePath: claims.filePath,
516 cause,
517 }),
518 ),
519 Effect.orElseSucceed(() => null),
520 );
521 return faviconPath === claims.filePath
522 ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
523 : null;
524 }
525
526 const decodedPath = decodeRelativePath(relativePath);
527 if (decodedPath === null) return null;
528 const path = yield* Path.Path;
529 if (claims.kind === "workspace-file-exact") {
530 if (decodedPath !== path.basename(claims.relativePath)) return null;
531 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
532 workspaceRoot: claims.workspaceRoot,
533 relativePath: claims.relativePath,
534 });
535 return exactWorkspaceFile
536 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
537 : null;
538 }
539 const segments = decodedPath.split(/[\\/]/);
540 if (
541 decodedPath.length === 0 ||
542 decodedPath.includes("\0") ||
543 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
544 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
545 ) {
546 return null;
547 }
548 const joinedRelativePath =
549 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
550 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
551 workspaceRoot: claims.workspaceRoot,
552 relativePath: joinedRelativePath,
553 });
554 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
555});