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