Open History to see the last commit
1import {
2 ATTACHMENT_UPLOAD_URL_TTL_MS,
3 type AttachmentCreateUploadUrlInput,
4 AttachmentUploadSigningKeyError,
5} from "@t3tools/contracts";
6import * as Clock from "effect/Clock";
7import * as Crypto from "effect/Crypto";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import type * as HttpServerRequest from "effect/http/HttpServerRequest";
15
16import {
17 attachmentFileExtension,
18 createPendingAttachmentId,
19 parseThreadSegmentFromAttachmentId,
20 PENDING_ATTACHMENT_THREAD_SEGMENT,
21 resolveAttachmentPathById,
22 sweepStalePendingAttachments,
23} from "../attachmentStore.ts";
24import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
25import {
26 base64UrlDecodeUtf8,
27 base64UrlEncode,
28 signPayload,
29 timingSafeEqualBase64Url,
30} from "../auth/utils.ts";
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as ServerConfig from "../config.ts";
33import { inferImageExtension } from "../imageMime.ts";
34
35export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
36
37const SIGNING_SECRET_NAME = "asset-access-signing-key";
38const PENDING_ATTACHMENT_SWEEP_INTERVAL_MS = 15 * 60_000;
39const lastPendingSweepByDirectory = new Map<string, number>();
40
41const AttachmentUploadClaims = Schema.Struct({
42 version: Schema.Literal(1),
43 kind: Schema.Literal("attachment-upload"),
44 type: Schema.Literals(["image", "file"]).pipe(
45 Schema.withDecodingDefault(Effect.succeed("image" as const)),
46 ),
47 attachmentId: Schema.String,
48 name: Schema.String,
49 mimeType: Schema.String,
50 sizeBytes: Schema.Number,
51 expiresAt: Schema.Number,
52});
53export type AttachmentUploadClaims = typeof AttachmentUploadClaims.Type;
54
55const attachmentUploadClaimsJson = Schema.fromJsonString(AttachmentUploadClaims);
56const decodeAttachmentUploadClaims = Schema.decodeUnknownOption(attachmentUploadClaimsJson);
57const encodeAttachmentUploadClaims = Schema.encodeSync(attachmentUploadClaimsJson);
58
59function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null {
60 try {
61 return Option.getOrNull(decodeAttachmentUploadClaims(base64UrlDecodeUtf8(encodedPayload)));
62 } catch {
63 return null;
64 }
65}
66
67const loadSigningSecret = Effect.gen(function* () {
68 const secretStore = yield* ServerSecretStore.ServerSecretStore;
69 return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
70});
71
72export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
73 input: AttachmentCreateUploadUrlInput,
74) {
75 const secret = yield* loadSigningSecret.pipe(
76 Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
77 );
78 const config = yield* ServerConfig.ServerConfig;
79 const nowMs = yield* Clock.currentTimeMillis;
80 const previousSweep = lastPendingSweepByDirectory.get(config.attachmentsDir);
81 if (
82 previousSweep === undefined ||
83 nowMs - previousSweep >= PENDING_ATTACHMENT_SWEEP_INTERVAL_MS
84 ) {
85 lastPendingSweepByDirectory.set(config.attachmentsDir, nowMs);
86 const swept = sweepStalePendingAttachments({
87 attachmentsDir: config.attachmentsDir,
88 nowMs,
89 });
90 if (swept.deleted > 0) {
91 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
92 }
93 }
94
95 const attachmentType = input.type ?? "image";
96 const attachmentId = createPendingAttachmentId(
97 attachmentType === "file" ? attachmentFileExtension(input.name) : undefined,
98 );
99 const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
100 const encodedPayload = base64UrlEncode(
101 encodeAttachmentUploadClaims({
102 version: 1,
103 kind: "attachment-upload",
104 type: attachmentType,
105 attachmentId,
106 name: input.name,
107 mimeType: input.mimeType,
108 sizeBytes: input.sizeBytes,
109 expiresAt,
110 }),
111 );
112
113 return {
114 attachmentId,
115 relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,
116 expiresAt,
117 };
118});
119
120export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
121 token: string,
122) {
123 const [encodedPayload, signature, unexpectedSegment] = token.split(".");
124 if (!encodedPayload || !signature || unexpectedSegment) {
125 return null;
126 }
127
128 const secret = yield* loadSigningSecret.pipe(
129 Effect.tapError((cause) =>
130 Effect.logError("Failed to load the attachment upload signing key.", { cause }),
131 ),
132 Effect.orElseSucceed(() => null),
133 );
134 if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {
135 return null;
136 }
137
138 const claims = decodeClaims(encodedPayload);
139 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) {
140 return null;
141 }
142 return claims;
143});
144
145export type StoreAttachmentUploadResult =
146 | { readonly ok: true }
147 | { readonly ok: false; readonly status: number; readonly detail: string };
148
149export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
150 claims: AttachmentUploadClaims,
151 body: Uint8Array | HttpServerRequest.HttpServerRequest["stream"],
152) {
153 if (body instanceof Uint8Array && body.byteLength !== claims.sizeBytes) {
154 return {
155 ok: false,
156 status: 400,
157 detail: `Body was ${body.byteLength} bytes, expected ${claims.sizeBytes}.`,
158 } satisfies StoreAttachmentUploadResult;
159 }
160
161 const config = yield* ServerConfig.ServerConfig;
162 const extension =
163 claims.type === "file"
164 ? attachmentFileExtension(claims.name)
165 : inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name });
166 const relativePath = `${claims.attachmentId}${extension}`;
167 const finalPath = resolveAttachmentRelativePath({
168 attachmentsDir: config.attachmentsDir,
169 relativePath,
170 });
171 const crypto = yield* Crypto.Crypto;
172 const partId = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
173 const partPath = resolveAttachmentRelativePath({
174 attachmentsDir: config.attachmentsDir,
175 relativePath: `${relativePath}.${partId}.part`,
176 });
177 if (!finalPath || !partPath) {
178 return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
179 }
180
181 const fileSystem = yield* FileSystem.FileSystem;
182 const path = yield* Path.Path;
183 let receivedBytes = 0;
184 const bodyStream = body instanceof Uint8Array ? Stream.make(body) : body;
185 return yield* Effect.gen(function* () {
186 yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
187 yield* Stream.run(
188 bodyStream.pipe(
189 Stream.takeWhile((chunk) => {
190 receivedBytes += chunk.byteLength;
191 return receivedBytes <= claims.sizeBytes;
192 }),
193 ),
194 fileSystem.sink(partPath),
195 );
196 if (receivedBytes !== claims.sizeBytes) {
197 return {
198 ok: false,
199 status: 400,
200 detail: `Body was ${receivedBytes} bytes, expected ${claims.sizeBytes}.`,
201 } satisfies StoreAttachmentUploadResult;
202 }
203 yield* fileSystem.rename(partPath, finalPath);
204 return { ok: true } satisfies StoreAttachmentUploadResult;
205 }).pipe(
206 Effect.catch((cause) =>
207 Effect.logError("Failed to persist attachment upload.", {
208 attachmentId: claims.attachmentId,
209 cause,
210 }).pipe(
211 Effect.as({
212 ok: false,
213 status: 500,
214 detail: "Failed to persist upload.",
215 } satisfies StoreAttachmentUploadResult),
216 ),
217 ),
218 Effect.ensuring(
219 fileSystem.remove(partPath, { force: true }).pipe(Effect.orElseSucceed(() => undefined)),
220 ),
221 );
222});
223
224export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
225 attachmentId: string,
226) {
227 if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
228 return;
229 }
230
231 const config = yield* ServerConfig.ServerConfig;
232 const attachmentPath = resolveAttachmentPathById({
233 attachmentsDir: config.attachmentsDir,
234 attachmentId,
235 });
236 if (!attachmentPath) {
237 return;
238 }
239
240 const fileSystem = yield* FileSystem.FileSystem;
241 yield* fileSystem.remove(attachmentPath, { force: true }).pipe(Effect.orElseSucceed(() => {}));
242});