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

AssetAccess.ts

429 lines14.3 KB

1import type { AssetResource } from "@v12/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 "@v12/contracts";
16import {
17 isWorkspaceImagePreviewPath,
18 isWorkspacePreviewEntryPath,
19 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
20 WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
21} from "@v12/shared/filePreview";
22import { PROJECT_FAVICON_FALLBACK_MARKER } from "@v12/shared/projectFavicon";
23import * as Clock from "effect/Clock";
24import * as Effect from "effect/Effect";
25import * as FileSystem from "effect/FileSystem";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as PlatformError from "effect/PlatformError";
29import * as Schema from "effect/Schema";
30​
31import {
32 base64UrlDecodeUtf8,
33 base64UrlEncode,
34 signPayload,
35 timingSafeEqualBase64Url,
36} from "../auth/utils.ts";
37import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
38import { resolveAttachmentPathById } from "../attachmentStore.ts";
39import * as ServerConfig from "../config.ts";
40import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
41import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
42​
43export const ASSET_ROUTE_PREFIX = "/api/assets";
44​
45const SIGNING_SECRET_NAME = "asset-access-signing-key";
46const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
47const PREVIEW_ASSET_EXTENSIONS = new Set([
48 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
49 ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
50 ".css",
51 ".js",
52 ".mjs",
53 ".otf",
54 ".ttf",
55 ".woff",
56 ".woff2",
57]);
58​
59const AssetClaimsSchema = Schema.Union([
60 Schema.Struct({
61 version: Schema.Literal(1),
62 kind: Schema.Literal("workspace-file"),
63 workspaceRoot: Schema.String,
64 baseRelativePath: Schema.String,
65 expiresAt: Schema.Number,
66 }),
67 Schema.Struct({
68 version: Schema.Literal(1),
69 kind: Schema.Literal("workspace-file-exact"),
70 workspaceRoot: Schema.String,
71 relativePath: Schema.String,
72 expiresAt: Schema.Number,
73 }),
74 Schema.Struct({
75 version: Schema.Literal(1),
76 kind: Schema.Literal("attachment"),
77 attachmentId: Schema.String,
78 expiresAt: Schema.Number,
79 }),
80 Schema.Struct({
81 version: Schema.Literal(1),
82 kind: Schema.Literal("project-favicon"),
83 workspaceRoot: Schema.String,
84 relativePath: Schema.NullOr(Schema.String),
85 expiresAt: Schema.Number,
86 }),
87]);
88type AssetClaims = typeof AssetClaimsSchema.Type;
89​
90const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
91const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
92const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
93​
94export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
95​
96function decodeClaims(encodedPayload: string): AssetClaims | null {
97 try {
98 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
99 } catch {
100 return null;
101 }
103​
104function decodeRelativePath(value: string): string | null {
105 try {
106 return decodeURIComponent(value);
107 } catch {
108 return null;
109 }
111​
112const optionOnNotFound = <A, R>(
113 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
114): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
115 effect.pipe(
116 Effect.map(Option.some),
117 Effect.catchTags({
118 PlatformError: (error) =>
119 error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
120 }),
121 );
122​
123const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
124 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
125 const fileSystem = yield* FileSystem.FileSystem;
126 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
127 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
128 Effect.map(Option.some),
129 Effect.catchTags({
130 WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
131 }),
132 );
133 if (Option.isNone(resolved)) return null;
134​
135 const [canonicalRoot, canonicalFile] = yield* Effect.all([
136 optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
137 optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
138 ]);
139 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
140​
141 const path = yield* Path.Path;
142 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
143 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
144​
145 const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
146 return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
147 },
148);
149​
150const resolveCanonicalWorkspaceFileForRequest = (input: {
151 readonly workspaceRoot: string;
152 readonly relativePath: string;
153}) =>
154 resolveCanonicalWorkspaceFile(input).pipe(
155 Effect.tapError((cause) =>
156 Effect.logError("Failed to resolve canonical asset path.", {
157 workspaceRoot: input.workspaceRoot,
158 relativePath: input.relativePath,
159 cause,
160 }),
161 ),
162 Effect.orElseSucceed(() => null),
163 );
164​
165export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
166 readonly resource: AssetResource;
167 readonly workspaceRoot?: string;
168}) {
169 const fileSystem = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
172 const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
173 let claims: AssetClaims;
174 let fileName: string;
175​
176 switch (input.resource._tag) {
177 case "workspace-file": {
178 if (!input.workspaceRoot) {
179 return yield* new AssetWorkspaceContextNotFoundError({
180 resource: input.resource,
181 });
182 }
183 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
184 Effect.mapError(
185 (cause) =>
186 new AssetWorkspaceRootNormalizationError({
187 resource: input.resource,
188 cause,
189 }),
190 ),
191 );
192 const relativePath = path.isAbsolute(input.resource.path)
193 ? path.relative(workspaceRoot, input.resource.path)
194 : input.resource.path;
195 const resolved = yield* workspacePaths
196 .resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
197 .pipe(
198 Effect.mapError(
199 (cause) =>
200 new AssetWorkspacePathValidationError({
201 resource: input.resource,
202 cause,
203 }),
204 ),
205 );
206 if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
207 return yield* new AssetPreviewTypeValidationError({
208 resource: input.resource,
209 });
210 }
211 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
212 workspaceRoot,
213 relativePath: resolved.relativePath,
214 }).pipe(
215 Effect.mapError(
216 (cause) =>
217 new AssetWorkspaceAssetInspectionError({
218 resource: input.resource,
219 cause,
220 }),
221 ),
222 );
223 if (!canonicalFile) {
224 return yield* new AssetWorkspaceAssetNotFoundError({
225 resource: input.resource,
226 });
227 }
228 const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
229 Effect.mapError(
230 (cause) =>
231 new AssetWorkspaceResolutionError({
232 resource: input.resource,
233 cause,
234 }),
235 ),
236 );
237 claims = isWorkspaceImagePreviewPath(resolved.relativePath)
238 ? {
239 version: 1,
240 kind: "workspace-file-exact",
241 workspaceRoot: canonicalWorkspaceRoot,
242 relativePath: resolved.relativePath,
243 expiresAt,
244 }
245 : {
246 version: 1,
247 kind: "workspace-file",
248 workspaceRoot: canonicalWorkspaceRoot,
249 baseRelativePath: path.dirname(resolved.relativePath),
250 expiresAt,
251 };
252 fileName = path.basename(resolved.relativePath);
253 break;
254 }
255 case "attachment": {
256 const config = yield* ServerConfig.ServerConfig;
257 const attachmentPath = resolveAttachmentPathById({
258 attachmentsDir: config.attachmentsDir,
259 attachmentId: input.resource.attachmentId,
260 });
261 if (!attachmentPath) {
262 return yield* new AssetAttachmentNotFoundError({
263 resource: input.resource,
264 });
265 }
266 claims = {
267 version: 1,
268 kind: "attachment",
269 attachmentId: input.resource.attachmentId,
270 expiresAt,
271 };
272 fileName = path.basename(attachmentPath);
273 break;
274 }
275 case "project-favicon": {
276 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
277 Effect.mapError(
278 (cause) =>
279 new AssetWorkspaceRootNormalizationError({
280 resource: input.resource,
281 cause,
282 }),
283 ),
284 );
285 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
286 const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
287 Effect.mapError(
288 (cause) =>
289 new AssetProjectFaviconResolutionError({
290 resource: input.resource,
291 cause,
292 }),
293 ),
294 );
295 const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
296 if (
297 relativePath &&
298 !(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
299 Effect.mapError(
300 (cause) =>
301 new AssetProjectFaviconInspectionError({
302 resource: input.resource,
303 cause,
304 }),
305 ),
306 ))
307 ) {
308 return yield* new AssetProjectFaviconNotFoundError({
309 resource: input.resource,
310 });
311 }
312 claims = {
313 version: 1,
314 kind: "project-favicon",
315 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
316 Effect.mapError(
317 (cause) =>
318 new AssetWorkspaceResolutionError({
319 resource: input.resource,
320 cause,
321 }),
322 ),
323 ),
324 relativePath,
325 expiresAt,
326 };
327 fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
328 break;
329 }
330 }
331​
332 const secretStore = yield* ServerSecretStore.ServerSecretStore;
333 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
334 Effect.mapError(
335 (cause) =>
336 new AssetSigningKeyLoadError({
337 resource: input.resource,
338 cause,
339 }),
340 ),
341 );
342 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
343 const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
344 return {
345 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
346 expiresAt,
347 };
348});
349​
350export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
351 token: string,
352 relativePath: string,
353) {
354 const [encodedPayload, signature] = token.split(".");
355 if (!encodedPayload || !signature) return null;
356​
357 const secretStore = yield* ServerSecretStore.ServerSecretStore;
358 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
359 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
360 Effect.orElseSucceed(() => null),
361 );
362 if (!signingSecret) return null;
363 if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
364​
365 const claims = decodeClaims(encodedPayload);
366 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
367​
368 if (claims.kind === "attachment") {
369 const config = yield* ServerConfig.ServerConfig;
370 const attachmentPath = resolveAttachmentPathById({
371 attachmentsDir: config.attachmentsDir,
372 attachmentId: claims.attachmentId,
373 });
374 if (!attachmentPath) return null;
375 const fileSystem = yield* FileSystem.FileSystem;
376 const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
377 Effect.tapError((cause) =>
378 Effect.logError("Failed to inspect attachment asset.", {
379 attachmentId: claims.attachmentId,
380 path: attachmentPath,
381 cause,
382 }),
383 ),
384 Effect.orElseSucceed(() => Option.none()),
385 );
386 return Option.isSome(info) && info.value.type === "File"
387 ? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
388 : null;
389 }
390​
391 if (claims.kind === "project-favicon") {
392 if (claims.relativePath === null) return null;
393 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
394 workspaceRoot: claims.workspaceRoot,
395 relativePath: claims.relativePath,
396 });
397 return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
398 }
399​
400 const decodedPath = decodeRelativePath(relativePath);
401 if (decodedPath === null) return null;
402 const path = yield* Path.Path;
403 if (claims.kind === "workspace-file-exact") {
404 if (decodedPath !== path.basename(claims.relativePath)) return null;
405 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
406 workspaceRoot: claims.workspaceRoot,
407 relativePath: claims.relativePath,
408 });
409 return exactWorkspaceFile
410 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
411 : null;
412 }
413 const segments = decodedPath.split(/[\\/]/);
414 if (
415 decodedPath.length === 0 ||
416 decodedPath.includes("\0") ||
417 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
418 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
419 ) {
420 return null;
421 }
422 const joinedRelativePath =
423 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
424 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
425 workspaceRoot: claims.workspaceRoot,
426 relativePath: joinedRelativePath,
427 });
428 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
429});