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

AssetAccess.ts

524 lines18.0 KB

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