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

AssetAccess.ts

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