forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAssetAccess.ts
More file actions
758 lines (728 loc) · 27.3 KB
/
Copy pathAssetAccess.ts
File metadata and controls
758 lines (728 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
import type { AssetResource } from "@t3tools/contracts";
import {
AssetAttachmentNotFoundError,
AssetPreviewTypeValidationError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
AssetProjectFaviconResolutionError,
AssetSigningKeyLoadError,
AssetWorkspaceAssetInspectionError,
AssetWorkspaceAssetNotFoundError,
AssetWorkspaceContextNotFoundError,
AssetWorkspacePathValidationError,
AssetWorkspaceResolutionError,
AssetWorkspaceRootNormalizationError,
ToolActivityNativeAppReference,
} from "@t3tools/contracts";
import {
hostPreviewMimeTypeFromExtension,
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import {
IMAGE_DIMENSIONS_HEADER_BYTES,
readImageDimensions,
type ImageDimensions,
} from "@t3tools/shared/imageDimensions";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
const PROJECT_FAVICON_VERSION_PREFIX = "v";
const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
// Extensions a document viewer may request inline. The extension comes from
// the attachment id the server assigned, never from the client's mime type.
const INLINE_DOCUMENT_EXTENSIONS = new Set(["pdf", "html", "htm"]);
const INLINE_DOCUMENT_MIME_TYPES: Record<string, string> = {
pdf: "application/pdf",
html: "text/html",
htm: "text/html",
};
const PREVIEW_ASSET_EXTENSIONS = new Set([
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
".css",
".js",
".mjs",
".otf",
".ttf",
".woff",
".woff2",
]);
const AssetClaimsSchema = Schema.Union([
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file"),
workspaceRoot: Schema.String,
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file-exact"),
workspaceRoot: Schema.String,
relativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("media-file-exact"),
filePath: Schema.String,
device: Schema.String,
inode: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
attachmentId: Schema.String,
/** Decided at mint time. Absent tokens (from before this field) serve
inline, which is only ever the image case. */
download: Schema.optionalKey(Schema.Boolean),
/** Display name and mime the caller supplied at mint time; drive the
download filename and Content-Type. */
fileName: Schema.optionalKey(Schema.String),
mimeType: Schema.optionalKey(Schema.String),
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("project-favicon"),
workspaceRoot: Schema.String,
relativePath: Schema.NullOr(Schema.String),
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("project-favicon-external"),
filePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("native-app-icon"),
app: ToolActivityNativeAppReference,
expiresAt: Schema.Number,
}),
]);
type AssetClaims = typeof AssetClaimsSchema.Type;
const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = {
readonly kind: "file";
readonly path: string;
readonly download?: boolean;
readonly fileName?: string;
readonly mimeType?: string;
readonly file?: OpenMediaFile;
};
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
} catch {
return null;
}
}
function decodeRelativePath(value: string): string | null {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
const optionOnNotFound = <A, R>(
effect: Effect.Effect<A, PlatformError.PlatformError, R>,
): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>
effect.pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
}),
);
const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
filePath: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
if (Option.isNone(canonicalFile)) return null;
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
});
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
const fileSystem = yield* FileSystem.FileSystem;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
Effect.map(Option.some),
Effect.catchTags({
WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),
}),
);
if (Option.isNone(resolved)) return null;
const [canonicalRoot, canonicalFile] = yield* Effect.all([
optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
]);
if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
const path = yield* Path.Path;
const relative = path.relative(canonicalRoot.value, canonicalFile.value);
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
},
);
const resolveCanonicalWorkspaceFileForRequest = (input: {
readonly workspaceRoot: string;
readonly relativePath: string;
}) =>
resolveCanonicalWorkspaceFile(input).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to resolve canonical asset path.", {
workspaceRoot: input.workspaceRoot,
relativePath: input.relativePath,
cause,
}),
),
Effect.orElseSucceed(() => null),
);
/**
* Reads pixel dimensions from an image's header so clients can reserve the
* exact box before the bytes arrive. Best effort: an unreadable or unsupported
* file just leaves the field out, and the client measures after decode. Only
* formats the parser understands are opened; SVG and the rest are skipped.
*/
const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
/** From the identity-checked, non-blocking handle the caller already holds. */
const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
Effect.map(readImageDimensions),
Effect.orElseSucceed((): ImageDimensions | null => null),
);
/**
* Opens through `openMediaFile` so a path swapped for a FIFO cannot block the
* request; a regular open would wait for a writer that never comes.
*/
const readImageDimensionsFromHeader = (filePath: string) =>
openMediaFile(filePath).pipe(
Effect.flatMap((file) =>
file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
),
Effect.scoped,
Effect.orElseSucceed((): ImageDimensions | null => null),
);
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
readonly resource: AssetResource;
readonly workspaceRoot?: string;
readonly projectFaviconPath?: string;
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
let claims: AssetClaims;
let fileName: string;
let sourcePath: string | undefined;
let imageDimensions: ImageDimensions | null = null;
switch (input.resource._tag) {
case "media-file": {
let requestedPath = input.resource.path;
if (!path.isAbsolute(requestedPath)) {
if (!input.workspaceRoot) {
return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
}
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.workspaceRoot)
.pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
),
);
requestedPath = path.resolve(workspaceRoot, requestedPath);
}
const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
Effect.mapError(
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
),
);
if (!canonicalFile) {
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
}
if (hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(
path.extname(canonicalFile).toLowerCase(),
);
const opened = yield* openMediaFile(canonicalFile).pipe(
Effect.flatMap((file) =>
file === null
? Effect.succeed(null)
: Effect.map(
wantsDimensions
? readImageDimensionsFromOpenFile(canonicalFile, file)
: Effect.succeed(null),
(dimensions) => ({
identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
dimensions,
}),
),
),
Effect.scoped,
Effect.mapError(
(cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
),
);
if (!opened) {
return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
}
const identity = opened.identity;
imageDimensions = opened.dimensions;
claims = {
version: 1,
kind: "media-file-exact",
filePath: canonicalFile,
...identity,
expiresAt,
};
fileName = path.basename(canonicalFile);
break;
}
case "workspace-file": {
if (!input.workspaceRoot) {
return yield* new AssetWorkspaceContextNotFoundError({
resource: input.resource,
});
}
const projectWorkspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.workspaceRoot)
.pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({
resource: input.resource,
cause,
}),
),
);
const projectRelativePath = path.isAbsolute(input.resource.path)
? path.relative(projectWorkspaceRoot, input.resource.path)
: input.resource.path;
const isAbsoluteOutsideProject =
path.isAbsolute(input.resource.path) &&
(projectRelativePath.startsWith("..") || path.isAbsolute(projectRelativePath));
const workspaceRoot = isAbsoluteOutsideProject
? yield* workspacePaths.normalizeWorkspaceRoot(path.dirname(input.resource.path)).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({
resource: input.resource,
cause,
}),
),
)
: projectWorkspaceRoot;
const relativePath = isAbsoluteOutsideProject
? path.basename(input.resource.path)
: projectRelativePath;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(
Effect.mapError(
(cause) =>
new AssetWorkspacePathValidationError({
resource: input.resource,
cause,
}),
),
);
if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {
return yield* new AssetPreviewTypeValidationError({
resource: input.resource,
});
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
relativePath: resolved.relativePath,
}).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceAssetInspectionError({
resource: input.resource,
cause,
}),
),
);
if (!canonicalFile) {
return yield* new AssetWorkspaceAssetNotFoundError({
resource: input.resource,
});
}
const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
);
if (HEADER_IMAGE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
imageDimensions = yield* readImageDimensionsFromHeader(canonicalFile);
}
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
? {
version: 1,
kind: "workspace-file-exact",
workspaceRoot: canonicalWorkspaceRoot,
relativePath: resolved.relativePath,
expiresAt,
}
: {
version: 1,
kind: "workspace-file",
workspaceRoot: canonicalWorkspaceRoot,
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
fileName = path.basename(resolved.relativePath);
break;
}
case "attachment": {
const config = yield* ServerConfig.ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: input.resource.attachmentId,
});
if (!attachmentPath) {
return yield* new AssetAttachmentNotFoundError({
resource: input.resource,
});
}
// Generic files carry their extension inside the attachment id (that
// shape resolves the on-disk path); images do not. Videos and images
// render inline. Other generic files download, unless a document viewer
// asked for inline and the stored extension is one a browser can show.
const extension = parseAttachmentFileExtension(input.resource.attachmentId);
const isGenericFile = extension !== null;
const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
const inlineDocumentMimeType =
input.resource.disposition === "inline" &&
extension !== null &&
INLINE_DOCUMENT_EXTENSIONS.has(extension)
? INLINE_DOCUMENT_MIME_TYPES[extension]
: undefined;
if (!isGenericFile) {
imageDimensions = yield* readImageDimensionsFromHeader(attachmentPath);
}
claims = {
version: 1,
kind: "attachment",
attachmentId: input.resource.attachmentId,
...(isGenericFile && !isVideo && inlineDocumentMimeType === undefined
? { download: true }
: {}),
...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
...(inlineDocumentMimeType !== undefined
? { mimeType: inlineDocumentMimeType }
: input.resource.mimeType !== undefined
? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
: {}),
expiresAt,
};
fileName = input.resource.fileName ?? path.basename(attachmentPath);
break;
}
case "project-favicon": {
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceRootNormalizationError({
resource: input.resource,
cause,
}),
),
);
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const faviconPath = yield* faviconResolver
.resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
.pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconResolutionError({
resource: input.resource,
cause,
}),
),
);
const isExternalOverride =
faviconPath !== null &&
input.projectFaviconPath !== undefined &&
path.isAbsolute(input.projectFaviconPath) &&
path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
const relativePath =
faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
sourcePath = sourceFaviconPath ?? undefined;
const canonicalFaviconPath = sourceFaviconPath
? yield* (
isExternalOverride
? resolveCanonicalFile(sourceFaviconPath)
: resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconInspectionError({
resource: input.resource,
cause,
}),
),
)
: null;
if (sourceFaviconPath && !canonicalFaviconPath) {
return yield* new AssetProjectFaviconNotFoundError({
resource: input.resource,
});
}
claims =
isExternalOverride && canonicalFaviconPath
? {
version: 1,
kind: "project-favicon-external",
filePath: canonicalFaviconPath,
expiresAt,
}
: {
version: 1,
kind: "project-favicon",
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
),
relativePath,
expiresAt,
};
if (sourceFaviconPath && canonicalFaviconPath) {
const crypto = yield* Crypto.Crypto;
const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconInspectionError({
resource: input.resource,
cause,
}),
),
);
const revision = yield* crypto.digest("SHA-256", faviconBytes).pipe(
Effect.map(Encoding.encodeHex),
Effect.mapError(
(cause) =>
new AssetProjectFaviconInspectionError({
resource: input.resource,
cause,
}),
),
);
fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
} else {
fileName = PROJECT_FAVICON_FALLBACK_MARKER;
}
break;
}
case "native-app-icon": {
claims = {
version: 1,
kind: "native-app-icon",
app: input.resource.app,
expiresAt,
};
fileName = "native-app-icon.png";
break;
}
}
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
Effect.mapError(
(cause) =>
new AssetSigningKeyLoadError({
resource: input.resource,
cause,
}),
),
);
if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
const issuedAt = yield* Clock.currentTimeMillis;
expiresAt =
(Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
PROJECT_FAVICON_TOKEN_BUCKET_MS;
claims = { ...claims, expiresAt };
}
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
return {
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
expiresAt,
...(sourcePath !== undefined ? { sourcePath } : {}),
...(imageDimensions !== null ? { imageDimensions } : {}),
};
});
export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
token: string,
relativePath: string,
) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
Effect.orElseSucceed(() => null),
);
if (!signingSecret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
const claims = decodeClaims(encodedPayload);
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
if (claims.kind === "attachment") {
const config = yield* ServerConfig.ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: claims.attachmentId,
});
if (!attachmentPath) return null;
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to inspect attachment asset.", {
attachmentId: claims.attachmentId,
path: attachmentPath,
cause,
}),
),
Effect.orElseSucceed(() => Option.none()),
);
return Option.isSome(info) && info.value.type === "File"
? ({
kind: "file",
path: attachmentPath,
...(claims.download ? { download: true } : {}),
...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
} satisfies ResolvedAsset)
: null;
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
}
if (claims.kind === "project-favicon-external") {
const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to resolve canonical asset path.", {
filePath: claims.filePath,
cause,
}),
),
Effect.orElseSucceed(() => null),
);
return faviconPath === claims.filePath
? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "native-app-icon") {
const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
}
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
if (claims.kind === "media-file-exact") {
if (decodedPath !== path.basename(claims.filePath)) return null;
const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to resolve canonical media path.", {
filePath: claims.filePath,
cause,
}),
),
Effect.orElseSucceed(() => null),
);
if (canonicalFile !== claims.filePath) return null;
const mimeType = hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
if (!mimeType) return null;
const file = yield* openMediaFile(canonicalFile, claims).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
),
Effect.orElseSucceed(() => null),
);
return file
? ({ kind: "file", path: canonicalFile, mimeType, file } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "workspace-file-exact") {
if (decodedPath !== path.basename(claims.relativePath)) return null;
const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return exactWorkspaceFile
? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
: null;
}
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
decodedPath.includes("\0") ||
segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
!PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
) {
return null;
}
const joinedRelativePath =
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: joinedRelativePath,
});
return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
});